DS

C++大作业代码(2) 2048游戏、图书管理程序等

C++大作业代码(2) 2048游戏、图书管理程序等

Posted by xuepro on June 14, 2019

2048游戏

//---------------widget.h-----------
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

#include <QWidget>
#include <QKeyEvent>
#include <QPainter>
#include <QTime>
#include <QPushButton>
#include <QTime>
#include <QtGlobal>
#include <QPushButton>


namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:

    explicit Widget(QWidget *parent = nullptr);
    int block[4][4]={0};      //宏定义一个int型数组,储存了方块

    void keyPressEvent(QKeyEvent *event);//输入键盘处理函数

    void move(int direction);//移动函数
    int  score();            //得到分数函数
    void judge();            //判断游戏是否结束函数
    int is_empty();          //判断是不是还有空的方块
    bool is_merge();         //判断相邻两个方块之间是否可以合并

    //定义储存横纵坐标类
    struct point{
        int i;
        int j;
    };
    struct point po[16]={};//用于存放空点的位置坐标
    //定义按钮用于重新开始游戏
    QPushButton *restart_button;
    //图形界面绘制函数
    void paint(QPainter *p,int num,QString color,int i,int j );
    void paintEvent(QPaintEvent *);


    ~Widget();
signals:


private:
    Ui::Widget *ui;
public slots: //定义槽函数,处理按钮点击事件
  void  start();
private slots:

};

#endif // WIDGET_H
//---------------------widget.cpp----------------------
#include "widget.h"
#include "ui_widget.h"

#include<QMessageBox>
#include<QtGlobal>
#include<cstdio>
#include<QPushButton>
#include<QDebug>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    restart_button = new  QPushButton(QStringLiteral("开始游戏"),this);
    restart_button->setGeometry(96,425,200,50);
    this->grabKeyboard();

    connect(restart_button,SIGNAL(clicked()),this,SLOT(start()));

}

Widget::~Widget()
{
    delete ui;
}
void Widget::start(){
     restart_button->setText(QStringLiteral("重新开始"));
    for(int i=0;i<4;i++)
        for (int j=0;j<4;j++) {
            block[i][j]=0;
        }
    int temp1=rand()%3;
    int temp2=rand()%3;
    int num1=temp1==0?2:4;
    int num2=temp2==0?2:4;

    //随机两个坐标
    int x1=rand()%4;
    int x2=rand()%4;
    int y1=rand()%4;
    int y2=rand()%4;
    //防止两个点相同
    while((x1==x2)&&(y1==y2)){
         x2=rand()%4;
         y2=rand()%4;
    }
    block[x1][y1]=num1;
    block[x2][y2]=num2;


    update();


}

//绘制方块函数
void Widget::paint(QPainter *p,int num,QString color,int i,int j){
    p->setBrush(QColor(color));
    p->drawRect(i*72+60,j*72+120,66,66);

    p->setFont(QFont(QString::fromLocal8Bit("华文琥珀"),10,QFont::Normal));
    if(num<64){
    p->setPen(QFont::Black);
    p->drawText(QRectF(i*72+60,j*72+120,66,66),QString::number(num),QTextOption(Qt::AlignCenter));}
    else {
        p->setPen(Qt::white);
        p->drawText(QRectF(i*72+60,j*72+120,66,66),QString::number(num),QTextOption(Qt::AlignCenter));
    }


}
void Widget::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.setBrush(QColor("#b8af9e"));
    p.setFont(QFont(QString::fromLocal8Bit("华文琥珀"),12,QFont::Normal));

    QString strscore;
   // p.setFont(QFont::)
    p.drawText(QPoint(10,20),QStringLiteral("用↑,↓,←,→分别控制方块上下左右移动"));
    p.setFont(QFont(QString::fromLocal8Bit("华文琥珀"),20,QFont::Normal));
    p.drawText(QPoint(10,60),QStringLiteral("分数:")+QString::number(score()));

    for(int i=0;i<4;i++)
        for(int j=0;j<4;j++){
            p.setPen(Qt::transparent);
            if(block[i][j] == 0){
                p.setBrush(QColor("#ccc0b2"));
                p.drawRect(i*72+60,j*72+120,66,66);

            }
            else if (block[i][j]==2){
               paint(&p,block[i][j],"#eee4da",i,j);

            }
            else if (block[i][j]==4){
                paint(&p,block[i][j],"#ece0c8",i,j);

            }
            else if (block[i][j]==8){
                paint(&p,block[i][j],"#f2b179",i,j);

            }
            else if (block[i][j]==16) {
                paint(&p,block[i][j],"#f59563",i,j);
            }
            else if (block[i][j]==32) {
                paint(&p,block[i][j],"#f57c5f",i,j);
            }
            else if (block[i][j]==64) {
                paint(&p,block[i][j],"#f65d38",i,j);
            }
            else if (block[i][j]==128) {
                paint(&p,block[i][j],"#edc171",i,j);
            }
            else if (block[i][j]==256) {
                paint(&p,block[i][j],"#edcc61",i,j);
            }
            else if (block[i][j]==512) {
                paint(&p,block[i][j],"#ecc850",i,j);
            }
            else if (block[i][j]==1024) {
                paint(&p,block[i][j],"#edc53f",i,j);
            }
            else if (block[i][j]==2048) {
                paint(&p,block[i][j],"#efc4ef",i,j);
            }

           }
}


//遍历数组获取得分
int Widget::score(){
    int grade=0;
    for(int col=0;col<4;++col)
    {
        for (int row = 0; row < 4; ++row)
        {
            grade+=block[col][row];
        }
    }
   return grade;
}
//根据键盘输入移动所有方块
void Widget::move(int direction){

    switch(direction){

      case 1://向上移动
        for(int i = 1; i < 4; ++i)
                {
                    for(int ci = i; ci >= 1; --ci)
                    {
                        for(int j = 0; j < 4; ++j)
                        {
                            //上一个格子为空
                            if(block[ci-1][j] == 0)
                            {
                                block[ci-1][j] = block[ci][j];
                                block[ci][j] = 0;
                            }
                            else
                            {
                                //合并
                                if(block[ci-1][j] == block[ci][j])
                                {
                                    block[ci - 1][j] *= 2;
                                    block[ci][j] = 0;
                                }

                            }
                        }
                    }
                }


        break;

      case 2 :

         for(int j = 2; j >= 0; --j)
                {
                    for(int cj = j; cj < 3; ++cj)
                    {
                        for(int i = 0; i < 4; ++i)
                        {
                            if(block[cj + 1][i] == 0)
                            {
                                block[cj + 1][i] = block[cj][i];
                                block[cj][i] = 0;
                            }
                            else
                            {

                                if(block[cj + 1][i] == block[cj][i])
                                {
                                    block[cj + 1][i] *= 2;
                                    block[cj][i] = 0;
                                }

                            }
                        }
                    }
                }



           break;
       case 3://向左移动

            for(int  i = 1; i < 4; ++i)
            {
                for(int ci = i; ci >= 1; --ci)
                {
                    for(int j = 0; j < 4; ++j)
                    {
                        //左边格子为空
                        if(block[j][ci-1] == 0)
                        {
                            block[j][ci - 1] = block[j][ci];
                            block[j][ci] = 0;
                        }
                        else
                        {
                            //合并有值相同的项
                            if(block[j][ci - 1] == block[j][ci])
                            {
                                block[j][ci - 1] *= 2;
                                block[j][ci] = 0;
                            }

                        }
                    }
                }
            }

        break;
       case 4:

        for(int  i = 2; i >= 0; --i)
                {
                    for(int ci = i; ci <= 4 - 2; ++ci)
                    {
                        for(int j = 0; j < 4; ++j)
                        {

                            if(block[j][ci + 1] == 0)
                            {
                                block[j][ci + 1] = block[j][ci];
                                block[j][ci] = 0;
                            }
                            else
                            {

                                if(block[j][ci + 1] == block[j][ci])
                                {
                                    block[j][ci + 1] *= 2;
                                    block[j][ci] = 0;
                                }

                            }
                        }
                    }
                }
                break;



   }

}
//处理键盘事件
void Widget::keyPressEvent(QKeyEvent *event)
     {
     //上下左右键控制在制定方向上移动
        switch(event->key())
        {
         case Qt::Key_Up:
              move(3);
              break;
         case Qt::Key_Down:
              move(4);
              break;
         case Qt::Key_Left:
              move(1);
              break;
         case Qt::Key_Right:
              move(2);
              break;
         default:return;//忽略其他按键
        }


        update();
        judge();
}

//判断游戏进程
int Widget::is_empty(){
    int  count=0;
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            if(block[i][j]==0){
                count+=1;
                //将空的方块坐标放入到储存方块位置的坐标里
                po[count-1].i=i;
                po[count-1].j=j;

            }
        }
    }
    return count;
}
//遍历每一个方块看他周围有没有可以与他合并的额方块
bool Widget::is_merge(){
    for(int i = 0 ; i < 4; ++i)
        {
            for(int j = 0; j < 3; ++j)
            {
                if( block[i][j] == block[i][j+1])
                {
                    return true;

                }
            }
        }

        for(int j = 0; j< 4; ++j)
        {
            for(int i = 0; i < 3; ++i)
            {
                if(block[i][j] == block[i+1][j])
                {
                    return true;

                }
            }


        }
        return false;
}
void Widget::judge(){
    //判断游戏是否胜利
    for(int i=0;i<4;i++)
    {
        for (int j = 0; j < 4; ++j) {
            if(block[i][j]==2048)break;

        }
    }
    //检测所有
    if(is_empty()==0){
        if(!is_merge())
        {
          QMessageBox::about(this,QStringLiteral("游戏失败"),QStringLiteral("您失败了, 当前分数:")+QString::number(score())+"       ");
        }
    }
    else if(is_empty()==1){
        int temp=rand()%3;
        int num=temp==0?2:4;
        block[po[0].i][po[0].j]=num;//将空值随机赋值出2,4
        update();
        if(!is_merge()){
        QMessageBox::about(this,QStringLiteral("游戏失败"),QStringLiteral("您失败了, 当前分数:")+QString::number(score())+"       ");
       }

    }
    else if (is_empty()==2) {
        int temp1=rand()%3;
        int temp2=rand()%3;
        int num1=temp1==0?4:2;
        int num2=temp2==0?4:2;
        block[po[0].i][po[0].j]=num1;
        block[po[1].i][po[1].j]=num2;
        update();
        if(!is_merge()){
        QMessageBox::about(this,QStringLiteral("游戏失败"),QStringLiteral("您失败了,当前分数:")+QString::number(score())+"       ");
       }

    }
    else if (is_empty()>2) {
        int temp1=rand()%3;
        int temp2=rand()%3;
        int num1=temp1==0?4:2;
        int num2=temp2==0?4:2;

        //在多个点中随机两个点
        int m1=rand()%(is_empty());
        int m2=rand()%(is_empty());
        //防止选择的两个点相同
        while(m2==m1){
             m2=rand()%(is_empty());

         }
        block[po[m1].i][po[m1].j]=num1;
        block[po[m2].i][po[m2].j]=num2;
        update();

       }

}
//-------------------------main.cpp----------------

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.setFixedSize(400,500);
    w.setWindowTitle("2048");
    w.setWindowIcon(QIcon(":/new/prefix1/2048.jpg"));
    w.show();

    return a.exec();
}

线性回归程序

// 线性回归.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// 作者:计科1704 1033170432 胡荣笙

#include "pch.h"
#include <iostream>
#include <stdlib.h>

using namespace std;
#define screen_height 60

using color = char;

class ChGL {
private:
	color* framebuffer{ nullptr };
	int framebuffer_width, framebuffer_height;
	color clear_color{ ' ' };

public:
	bool initWindow(int width, int height) {
		framebuffer = new color[width * height];
		if (!framebuffer) return false;
		framebuffer_width = width;
		framebuffer_height = height;
		clearWindow();
		return true;
	}

	void clearWindow() {
		for (int y = 0; y < framebuffer_height; y++)
			for (int x = 0; x < framebuffer_width; x++)
				framebuffer[y * framebuffer_width + x] = clear_color;
	}

	void destoryWindow() {
		delete[] framebuffer;
		framebuffer = nullptr;
	}

	void show() {
		for (int y = 0; y < framebuffer_height; y++) {
			for (int x = 0; x < framebuffer_width; x++)
				cout << framebuffer[y * framebuffer_width + x];
			cout << endl;
		}
	}

	void setPixel(const int x, const int y, color c = ' ') {
		framebuffer[(screen_height - y) * framebuffer_width + x] = c;
	}

	color getPixel(const int x, const int y) {
		return framebuffer[y * framebuffer_width + x];
	}

	void set_clear_color(color c) { clear_color = c; }

	color get_clear_color() { return clear_color; }

};

class plot_line :public ChGL {
public:
	void bresenham(int x0, int y0, int x1, int y1) {
		int i, x, y, dx, dy;
		float e = 0;
		dx = abs(x1 - x0);
		dy = abs(y1 - y0);
		e = -0.5; x = x0; y = y0;
		for (i = 0; i <= dx; i++) {
			setPixel(x, y, '*');
			x = x + 1;
			if (2 * (e + dy) >= dx) {
				y += 1;
				e = e + dy - dx;
			}
			else {
				e = e + dy;
			}
		}
	}
};

class gra_des {
public:
	double theta_matrix[6][2]{};

	double X[10][1]{
	9.16481174938805, 3.9617176989763605, 1.9118988617843014,
	4.770872353143195, 8.96268633959237, 4.347497877496233,
	0.7837488406009996, 9.003451281535993, 9.219537986787007,
	0.14895852444561486 };

	double Y[10]{
		19.3296234987761, 8.923435397952721, 4.823797723568603,
		10.54174470628639, 18.92537267267918474, 9.694995754992465, 2.567487681201999,
		19.006902563071986, 19.439075973574013, 1.2979170488912297 };

	const int m{ 10 }, n{ 2 };

	auto h_theta_x(double X0, double X1, const double theta[], const int n) {
		return (theta[0] * X0) + (theta[1] * X1);
	}

	auto cost_function(double g[], const double X[][2], const double* Y, const double theta[], const int m) {
		auto f{ 0. };
		for (auto j = 0; j != n; j++)
			g[j] = 0;
		for (int i = 0; i < m; i++) {
			auto h = h_theta_x(X[i][0], X[i][1], theta, n);
			auto h_y{ h - Y[i] };
			f += (h_y * h_y);
			for (int j = 0; j < n; j++)
				g[j] += (h_y * X[i][j]);
		}
		f /= (2 * m);
		for (int j = 0; j < n; j++)
			g[j] /= m;
		return f;
	}

	auto gradient_descent(double X[][2], double* Y, double theta[],
		double alpha, const int iterations, const int m, double* cost_history, double theta_easy[12]) {
		int flag = 0;
		for (auto iter = 0; iter <= iterations; iter++) {
			double g[2]{};
			auto f = cost_function(g, X, Y, theta, m);
			cost_history[iter] = f;
			for (auto j = 0; j < n; j++)
				theta[j] -= alpha * g[j];
			if (iter % 199 == 1) {
				for (int j = 0; j < n; j++) {
					theta_easy[flag] = theta[j];
					flag++;
				}
			}
		}
	}

	inline void initgd() {
		const int m{ 10 }, n{ 2 };

		gra_des gd;

		double train_X[m][n]{}, train_Y[m]{};
		for (int i = 0; i < m; i++) {
			train_X[i][0] = 1;
			train_X[i][1] = gd.X[i][0];
			train_Y[i] = gd.Y[i];
		}
		double theta[n]{};
		auto alpha(0.0001);
		double theta_easy[12]{};
		
		auto iterations{ 1000 };
		double cost_history[1000];
		gd.gradient_descent(train_X, train_Y, theta, alpha, iterations, m, cost_history, theta_easy);

		int flag = 0;
		for (int i = 0; i < 6; i++)
			for (int j = 0; j < 2; j++) {
				theta_matrix[i][j] = theta_easy[flag];
				flag++;
			}

		for (int j = 0; j != n; j++)
			cout << theta[j] << '\t';
		cout << endl;
		for (int j = 0; j != 1000; j++)
			if (j % 99 == 1)
				cout << j << '\t' << cost_history[j] << '\n';
		cout << '\n';
	}
};

class theta_show: public plot_line, gra_des{
public:

	gra_des gd;
	plot_line pl;
	
	inline void thetashow() {
		gd.initgd();
		for (int i = 0; i < 6; i++) {
			double y01[2]{};
			y01[0] = gd.theta_matrix[i][0] + gd.theta_matrix[i][1] * 0;
			y01[1] = gd.theta_matrix[i][0] + gd.theta_matrix[i][1] * 100;
			pl.bresenham(0, y01[0], 100, y01[1]);
		}
	}


};

int main()
{
	gra_des gd;
	plot_line pl;

	const int w = 120, h = 100;
	if (!pl.initWindow(w, h)) {
		return 1;
	}
	
	gd.initgd();
	for (int i = 0; i < 6; i++) {
		double y01[2]{};
		y01[0] = gd.theta_matrix[i][0] + gd.theta_matrix[i][1] * 0;
		y01[1] = gd.theta_matrix[i][0] + gd.theta_matrix[i][1] * 50;
		pl.bresenham(0, y01[0], 100, y01[1]);
	}

	pl.show();
	return 0;
	system("PAUSE");
}

图书借阅程序:

#include <iostream>//数据输入输出流
#include <string.h>//字符串操作函数
#include <stdio.h>//C的输入输出
#include <stdlib.h>//定义杂项函数及内存分配函数
#include <math.h>//C中的数学函数
#include <string.h>//c++中的string类 他不能用strcpy等c函数去操作
#include <vector>//STL vetor容器
#include <list>//STL list
#include <map>// STL map
#include <queue>// STL queue
#include <stack>//sTL stack
#include <bitset>//bitset可按位定义串
#include <algorithm>//STL各种算法 比如 swap sort merge max min 比较
#include <numeric>//常用数字操作 一般和algorithm搭配使用
#include <functional>//STL定义运算函数(代替运算符)
#include<limits.h>//定义各种数据类型最值常量
#include <fstream>
using namespace std;


class Student { // 学生类

private:
	int sno; // 学号
	char name[10]; // 姓名
	int book_number; // 图书编号
	int password;


public:
	Student() {
	    sno = 0;
	    name[10] ={'0'};
	    book_number = 0;
} // 构造函数

int getkey(){return password;}

	int getNumber() { return sno; } // 得到学生信息

	void Login(int number); // 登录

	void Borrow(); // 借书

	void Return(); // 还书

	void Show(); // 显示账号所有信息


};


typedef struct Att { // 定义结构体实现链表存储
	Student A;
	struct Att *next;
}ATT;


void Student::Login(int number) { // 登录
	cout << "           请输入姓名: " ;
	cin >> name;
	cout << "           请输入六位数字的密码: ";
	cin >> password;
          sno = number;
	cout<<"           登录成功!"<<endl;
}


void Student::Borrow() { // 借书
    int newkey;
    cout << "           请输入密码: " ;
	cin >> newkey;
	if(newkey!=password){
        cout << "           密码错误." << endl;
        return ;
	}
	system("cls");

	cout << "           ---------------- 图书借阅管理系统 ----------------" << endl;
	cout << "           以下是热门书籍: " <<endl;

	cout<<"           1、《论语》"<<endl;
	cout<<"           2、《看见》"<<endl;
	cout<<"           3、《活着》"<<endl;
	cout<<"           4、《茶花女》"<<endl;
	cout<<"           5、《小王子》"<<endl;
	cout<<"           6、《四世同堂》"<<endl;
	cout<<"           7、《你今天真好看》"<<endl;
	cout<<"           8、《她的世俗与高贵》"<<endl;
	cout<<"           9、《按自己的意愿过一生》"<<endl;
	cout<<"           是否有你想借阅的书(y/n): ";
	char st;
	cin >> st;
	if (st == 'n') {cout<<"           请输入你想借阅的书籍名称: ";
                              char bn[10];
                              cin >> bn;
                              book_number=16;
                                        }
          else {
                    cout << "           请输入想借的图书编号: " ;
                    int a;
                    cin>>a;
                    book_number = a;
          }
	system("cls");

	cout << "           ---------------- 图书借阅管理系统 ----------------" << endl;
          cout<<"           借书成功!"<<endl;
        cout<<"           最多可借三个月!"<<endl;
        cout<<"           请在三个月内归还." << endl;
}


void Student::Return() { // 还书
          system("cls");
	cout << "           ---------------- 图书借阅管理系统 ----------------" << endl;
	cout << "           你借的书编号是 " << book_number <<endl
            << "           请输入你想归还的图书编号:" ;
	int a=0;
          do {
                    cin >> a;
		if (a!=book_number) { cout << "           你未借此书,请重输 :"; }
                    else{cout<<"           还书成功!"<<endl;}

	} while (a!=book_number);
	book_number = 0;

}

void Student::Show() { // 显示账号所有信息
    int newkey;
    cout << "           请输入密码:" ;
	cin >> newkey;
	if(newkey!=password){
        cout << "           密码错误." << endl;
        return ;
	}
	system("cls");

	cout << "           ---------------- 图书借阅管理系统 ----------------" << endl;
	cout << "           学号 :" << sno <<endl
	<< "           姓名 : " << name <<endl
          << "           已借书编号 :  "<<book_number<<endl;
          cout<<"           是否导出借阅信息(y/n): ";
          char ac;
          cin>> ac;
          cout<<"           导出成功!"<<endl;
          ofstream outinfo("info.txt",ofstream::app);
          outinfo<<"学号 :" << sno <<endl
	<< "姓名 : " << name <<endl
          << "已借书编号 :  "<<book_number<<endl<<endl;
          outinfo.close();
}

void menu() { // 主界面
	cout << "           ---------------- 图书借阅管理系统 ----------------" << endl;
	cout << "           1、用户登录                                      " << endl;
	cout << "           2、我想借书                                      " << endl;
	cout << "           3、我想还书                                      " << endl;
	cout << "           4、借阅信息                                  " << endl;
	cout << "           0、退出                                          " << endl;
	cout << "           --------------------------------------------------" << endl<<endl;
	cout << "           请输入你想选择的服务编号(0-4): " ;
}


void fun() {
	ATT *A, *C, *serchp, *search, *fp;
	// A 为新结点指针 C为链表头指针 serchp 为尾指针指向最后一个结点
	//search 为 遍历链表指针 用于判断账号是否存在
	int number; // number 表示用户输入的账号
	C = (ATT*)malloc(sizeof(ATT));
	C->next = NULL; // 头结点为空(一直都没用)
	serchp = C;
	char c = '0', ch, c1;
	// c 用于判断是否 继续操作(主界面) ch 用于判断选择输入是否正确
		do {
			system("cls"); // 清屏

			menu(); // 显示主界面
			cin >> ch;
			while (ch<'0' || ch>'5') {
				cout << "           输入错误,请重输: ";
				cin >> ch;
				getchar();
			}

			switch (ch) { // 选择相应的操作
			case '1': // 登录
				cout << "           请输入学号:" ;
				search = serchp->next;
				do {
					if (search != NULL) {
						cout << "           此学号已存在,是否继续(y / n) " ;
						cin >> c1;
						if (c1 == 'n') {
							break;
						}
						else cout << "           请重输: " ;
					}
					cin >> number;
					search = C->next;
					while (search != NULL&&number != search->A.getNumber()) {
						search = search->next;
					}
				} while (search != NULL);
				if (c1 == 'n')break;
				A = (ATT*)malloc(sizeof(ATT)); // 申请新结点
				A->A.Login(number);
				A->next = NULL;
				serchp->next = A; // 将新结点插入链尾
				serchp = serchp->next;
				break;


			case '2': // 借书
				cout << "           请输入学号: ";
				search = C;
				do {
					if (search == NULL) {
						cout << "           学号不存在,是否继续 (y / n) " ;
						cin >> c1;
						if (c1 == 'n') {
							break;
						}
						else cout << "           请重输: " ;
					}
					cin >> number;
					search = C->next;
					while (search != NULL&&number != search->A.getNumber()) {
						search = search->next;
					}
				} while (search == NULL);
				if (c1 == 'n')break;
				search->A.Borrow();
				break;


			case '3': // 还书
				cout << "           请输入学号: " ;
				search = C;
				do {
					if (search == NULL) {
						cout << "           此学号不存在,是否继续(y / n) " ;
						cin >> c1;
						if (c1 == 'n') {
							break;
						}
						else cout << "           请重输: " ;
					}
					cin >> number;
					search = C->next;
					while (search != NULL&&number != search->A.getNumber()) {
						search = search->next;
					}
				} while (search == NULL);
				if (c1 == 'n')break;
				search->A.Return();
				break;


			case '4':  //显示所有信息
				cout << "           请输入学号: " ;
				search = C;
				do {
					if (search == NULL) {
						cout << "           学号不存在,是否继续(y / n) " ;
						cin >> c1;
						if (c1 == 'n') {
							break;
						}
						else cout << "           请重输: " ;
					}
					cin >> number;
					search = C->next;
					while (search != NULL&&number != search->A.getNumber()) {
						search = search->next;
					}
				} while (search == NULL);
				if (c1 == 'n')break;
				search->A.Show();
				break;

			case '0': // 退出系统
				cout << "           谢谢使用!." << endl;
				c = 'n';
				break;
			}
			if (c != 'n') {
				cout << "           是否继续 (y/n): " ;
				cin >> c;
			}
		} while (c == 'y' || c == 'Y');
}

int main() {
	fun();
	return 0;
}

简易租车程序

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
const int car_num = 5;//个体能租的最大汽车数量

class car {
	int carid;//车辆编号
	string carname;//车型
	double bill;//租金
	int flag{ 0 };//租赁标志
public:
	car() {}
	car(int a, string n, double b, int c) {
		carid = a;
		carname = n;
		bill = b;
		flag = c;
	}
	//车辆未租
	void in() {
		flag = 1;
	}
	//车辆已租
	void out() {
		flag = 0;
	}
	//得到租金
	double getbill() {
		return bill;
	}
	//得到车辆编号
	int getcarid() {
		return carid;
	}
	//设置租金
	void setbill(double b) {
		bill = b;
	}
	//设置车型
	void setcarname(string n) {
		carname = n;
	}
	//打印单个车辆信息
	void print() {
		cout << carid << "\t\t" << carname << "\t\t" << bill << "\t\t" << flag << endl;
	}
};

class client {
	string name;//用户名字
	int client_no;//用户id
	int carno[car_num]{ 0 };//记录租的车辆编号
	double check{ 0 };//总租金
public:
	client() {}
	client(int no, string name) {
		this->client_no = no;
		this->name = name;
	}
	//得到用户id
	int getno() { return client_no; }
	//修改用户名字
	void setname(string s) { name = s; }
	//借车
	void borrow(car a_car) {
		int i;
		for (i = 0; i < car_num; i++)
		{
			if (carno[i] == 0)
			{
				carno[i] = a_car.getcarid();
				check += a_car.getbill();
				break;
			}
		}
		if (i == car_num)
			cout << "该用户已达最大租车数量" << endl;
	}
	//还车
	void back(car a_car) {
		int i;
		for (i = 0; i < car_num; i++)
		{
			if (carno[i] == a_car.getcarid())
			{
				carno[i] = 0;
				check -= a_car.getbill();
				return;
			}
		}
		cout << "该用户未租编号为" << a_car.getcarid() << "的车" << endl;
	}
	//打印单条用户信息
	void print() {
		cout << client_no << "\t\t" << name << "\t\t" << check << "\t\t";
		for (int i = 0; i < car_num; i++)
		{
			if (carno[i] != 0) { cout << carno[i] << '#'; }
		}
		cout << endl;
	}
};

class client_db {
public:
	vector<client> clients;
	client_db() {
		client c1(1001, "张三");
		client c2(1002, "李四");
		client c3(1003, "王五");
		clients.push_back(c1);
		clients.push_back(c2);
		clients.push_back(c3);
	}
	//得到指定编号的用户位置
	int get_cli(int id) {
		for (int i = 0; i < clients.size(); i++)
		{
			if (clients[i].getno() == id)
				return i;
		}
		return -1;
	}
	//增加用户
	void addcli(client cli) {
		clients.push_back(cli);
	}
	//删除
	void delcli(int n) {
		int flag = 0;
		//使用erase删除,防止iter变成野指针
		for (vector<client>::iterator iter = clients.begin(); iter != clients.end(); )
		{
			if (iter->getno() == n)
			{
				iter = clients.erase(iter);
				flag = 1;
			}
			else
				iter++;
		}
		if (flag == 0)
			cout << "查无此户" << endl;
	}
	//打印所有用户
	void print() {
		printf("----------------客户信息----------------\n");
		printf("编号       姓名       租金($)    已租车辆编号\n");
		for (int i = 0; i < clients.size(); i++)
			clients[i].print();
	}
};

class car_db {
public:
	vector<car> cars;
	car_db() {
		car c1(9001, "大众", 200, 1);
		car c2(9002, "宝马", 300, 1);
		car c3(9003, "五菱", 50, 1);
		cars.push_back(c1);
		cars.push_back(c2);
		cars.push_back(c3);
	}
	//查询编号为id的车在vector中位置,返回car类型
	car get_car(int id) {
		int i;
		for (i = 0; i < cars.size(); i++)
		{
			if (cars[i].getcarid() == id)
				break;
		}
		return cars[i];
	}
	//查询编号为id的车在vector中位置,返回下标
	int get_car_no(int id) {
		int i;
		for (i = 0; i < cars.size(); i++)
		{
			if (cars[i].getcarid() == id)
				break;
		}
		return i;
	}
	//增加汽车信息
	void addcar(car c) {
		cars.push_back(c);
	}
	//删除汽车信息
	void delcar(int car_id) {
		int flag = 0;
		//使用erase删除,防止iter变成野指针
		for (vector<car>::iterator iter = cars.begin(); iter != cars.end(); )
		{
			if (iter->getcarid() == car_id)
			{
				iter = cars.erase(iter);
				flag = 1;
			}
			else
				iter++;
		}
		if (flag == 0)
			cout << "查无此车" << endl;
	}
	//打印所有汽车信息
	void print() {
		printf("----------------车辆信息----------------\n");
		printf("编号       车型       租金       出租情况\n");
		for (int i = 0; i < cars.size(); i++)
			cars[i].print();
	}
};

//全局变量:客户db、汽车db
client_db clidb;
car_db cardb;

//交互操作函数
void add_client() {//增加用户
	int num;
	string name;
	cout << "请输入编号:";
	cin >> num;
	cout << "请输入姓名:";
	cin >> name;
	client c(num, name);
	clidb.addcli(c);
}
void del_client() {//删除用户
	int num;
	cout << "请输入要删除的用户编号:";
	cin >> num;
	clidb.delcli(num);
}
void add_car() {//增加汽车
	int num;
	double rent;
	char name[2];
	cout << "请输入编号:";
	cin >> num;
	cout << "请输入车型:";
	cin >> name;
	cout << "请输入租金:";
	cin >> rent;
	car c(num, name, rent, 1);
	cardb.addcar(c);
}
void del_car() {//删除汽车
	int num;
	cout << "请输入要删除的车辆编号:";
	cin >> num;
	cardb.delcar(num);
}
void borrow_car() {//借车
	int cliid, carid, cliindex, carindex;
	car car_;
	cout << "请输入要借车的用户编号:";
	cin >> cliid;
	cout << "请输入要租的车的编号:";
	cin >> carid;
	cliindex = clidb.get_cli(cliid);
	car_ = cardb.get_car(carid);
	clidb.clients[cliindex].borrow(car_);
	carindex = cardb.get_car_no(carid);
	cardb.cars[carindex].out();
}
void back_car() {//还车
	int cliid, carid, cliindex, carindex;
	car car_;
	cout << "请输入要还车的用户编号:";
	cin >> cliid;
	cout << "请输入要还的车的编号:";
	cin >> carid;
	cliindex = clidb.get_cli(cliid);
	car_ = cardb.get_car(carid);
	clidb.clients[cliindex].back(car_);
	carindex = cardb.get_car_no(carid);
	cardb.cars[carindex].in();
}
void update_client() {
	int num, pos;
	string n;
	cout << "请输入要修改的用户编号:";
	cin >> num;
	cout << "请输入新的姓名:";
	cin >> n;
	pos = clidb.get_cli(num);
	clidb.clients[pos].setname(n);
	cout << "修改完成!" << endl;
}
void update_car() {
	int num, pos;
	double b;
	string n;
	cout << "请输入要修改的车辆编号:";
	cin >> num;
	cout << "请输入新的车型:";
	cin >> n;
	cout << "请输入租金:";
	cin >> b;
	pos = cardb.get_car_no(num);
	cardb.cars[pos].setcarname(n);
	cardb.cars[pos].setbill(b);
	cout << "修改完成!" << endl;
}
void new_main() {
	char fu;//用户输入
	while (true)
	{
		printf("-----------------欢迎-----------------\n");
		printf("a--查看用户                  b--查看车辆\n");
		printf("c--增加用户                  d--增加车辆\n");
		printf("e--删除用户                  f--删除车辆\n");
		printf("g--修改用户                  h--修改车辆\n");
		printf("i--用户借车                  j--用户还车\n");
		printf("0--退出                               \n");
		printf("-----------------欢迎-----------------\n");
		cin >> fu;
		if (fu == '0')  return;
		if (fu == 'a')  clidb.print();
		if (fu == 'b')  cardb.print();
		if (fu == 'c')  add_client();
		if (fu == 'd')  add_car();
		if (fu == 'e')  del_client();
		if (fu == 'f')  del_car();
		if (fu == 'g')  update_client();
		if (fu == 'h')  update_car();
		if (fu == 'i')  borrow_car();
		if (fu == 'j')  back_car();
		getchar();
		cout << "按回车继续" << endl;
		getchar();
	}
}

int main() {
	new_main();
	system("pause");
}

扫雷游戏


#include<stdio.h>

#include<windows.h>

#include<stdlib.h>

#include<time.h>

#include<conio.h>

#include<queue>

#include<ctype.h>

#define A 17	//地图的高

#define B 17	//地图的宽

#define C 30	//雷的总数

using namespace std;

 

//全局变量

DWORD a,b;

char map[A][B],news,spare;

int BoomTotalNum,floatx,floaty,flag[A][B],flagnum,mode,slect[A][B],game;

 

//颜色属性

const WORD FORE_BLUE  =  FOREGROUND_BLUE;	//蓝色文本属性

const WORD FORE_GREEN = FOREGROUND_GREEN;	//绿色文本属性

const WORD FORE_RED   =   FOREGROUND_RED;	//红色文本属性

 

//开垦地图结构体 

struct node {

	int x;

	int y;

};

queue <node> dui;

 

//打印位置

void position(int x,int y) {

	COORD pos={x,y};

	HANDLE Out=GetStdHandle(STD_OUTPUT_HANDLE);
//自定义了一个在VC++6.0中实现控制光标所在位置的函数
	SetConsoleCursorPosition(Out,pos);

}

 

//隐藏光标 

void Hide() {

	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);  

	CONSOLE_CURSOR_INFO CursorInfo;  

	GetConsoleCursorInfo(handle, &CursorInfo);//获取控制台光标信息  

	CursorInfo.bVisible = false; //隐藏控制台光标  

	SetConsoleCursorInfo(handle, &CursorInfo);//设置控制台光标状态   

}

 

//初始化

void Beginning() {

	while(!dui.empty()) {

		dui.pop();

	}

	game=1;

	//BoomTotalNum=C;

	floatx=A/2;

	floaty=B/2;

	flagnum=0;

	BoomTotalNum=C;

	mode=0;

	HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);    //获得标准输出设备句柄  

    CONSOLE_SCREEN_BUFFER_INFO csbi;                        //定义窗口缓冲区信息结构体  

    GetConsoleScreenBufferInfo(handle_out, &csbi);          //获得窗口缓冲区信息

    int x,y;

	srand((unsigned)time(0));

	for(int i=0;i<A;i++) for(int j=0;j<B;j++) {

		map[i][j]=' ';

		flag[i][j]=0;

		slect[i][j]=0;

	}

	while(BoomTotalNum) {

		x=rand()%A;

		y=rand()%B;

		if(map[x][y]==' ') {

			map[x][y]='@';

			BoomTotalNum--;

		}

	}

	SetConsoleTextAttribute(handle_out, FORE_GREEN);  

	for(int i=0;i<A;i++) {

		for(int j=0;j<B;j++) printf("█");

		printf("\n");

	}

	position(floaty*2,floatx);

	SetConsoleTextAttribute(handle_out, FORE_RED);  

	printf("");	//光标位置

	position(44,9);

	printf("扫雷模式");

	position(44,5);

	printf("剩余雷数:%d ",C-flagnum);

	SetConsoleTextAttribute(handle_out, FORE_GREEN);  

	position(5,22);

	printf("按“空格”切换模式");

	position(5,23);

	printf("按“Enter”确认");

	position(5,24);

	printf("按“方向键”选择方块"); 

	

}

 

//打印地图的一块儿 

void Lump(int xx,int yy) {

	switch(map[xx][yy]) {

		case '1' : printf("①");break;	//周围雷的数量(下同) 

		case '2' : printf("②");break;

		case '3' : printf("③");break;

		case '4' : printf("④");break;

		case '5' : printf("⑤");break;

		case '6' : printf("⑥");break;

		case '7' : printf("⑦");break;

		case '8' : printf("⑧");break;

		case ' ' :

			if(xx==floatx&&yy==floaty) {

				if(flag[xx][yy]==0) {

					if(mode%2==0) printf("");

					else printf("");

				}

				else printf("");

			}

			else {

				if(flag[xx][yy]==0) printf("█");

				else printf("");

			}

			break;

		case '@' :

			if(xx==floatx&&yy==floaty) {

				if(flag[xx][yy]==0) {

					if(mode%2==0) printf("");

					else printf("");

				}

				else printf("");

			}

			else {

				if(flag[xx][yy]==0) printf("█");

				else printf("");

			}

			break;

		case 'x' : if(floatx==xx&&floaty==yy) printf(""); else printf("  ");break;	//已经挖开的空白

	}

}

 

//移动光标

void Move() {

	HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);    //获得标准输出设备句柄  

    CONSOLE_SCREEN_BUFFER_INFO csbi;                        //定义窗口缓冲区信息结构体  

    GetConsoleScreenBufferInfo(handle_out, &csbi);          //获得窗口缓冲区信息

    int xxx,yyy;

    xxx=floatx;

    yyy=floaty;

	switch(news) {

		case 72 : floatx--;break;	//上 

		case 80 : floatx++;break;	//下 

		case 75 : floaty--;break;	//左 

		case 77 : floaty++;break;	//右 

	}

	if(floatx==-1) floatx=A-1; floatx%=A;	//两端穿模处理 

	if(floaty==-1) floaty=B-1; floaty%=B;

	

	position(yyy*2,xxx);

	SetConsoleTextAttribute(handle_out, FORE_GREEN);

	Lump(xxx,yyy);	//删除原位置

	

	if(map[floatx][floaty]=='x') {

		position(floaty*2,floatx);

		printf("  ");

	}

	

	position(floaty*2,floatx);

	SetConsoleTextAttribute(handle_out, FORE_BLUE);  

	Lump(floatx,floaty);	//更新新位置 

} 

 

//插旗和排雷模式切换 

void Mode() {

	HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);    //获得标准输出设备句柄  

    CONSOLE_SCREEN_BUFFER_INFO csbi;                        //定义窗口缓冲区信息结构体  

    GetConsoleScreenBufferInfo(handle_out, &csbi);          //获得窗口缓冲区信息

	mode++;

	SetConsoleTextAttribute(handle_out, FORE_BLUE);

	position(floaty*2,floatx);

	if(mode%2==0) printf("");

	else printf("");

	

	position(44,9);

	if(mode%2==0) {

		SetConsoleTextAttribute(handle_out, FORE_BLUE);  

		printf("扫雷模式");

	}

	else {

		SetConsoleTextAttribute(handle_out, FORE_RED);  

		printf("插旗模式");

	}

}

 

//该点周围地雷数 

int Boomnum(int xx,int yy) {

	int num=0;

	if((xx-1>=0)&&(yy-1>=0)&&(map[xx-1][yy-1]=='@')) num++;

	if((xx-1>=0)&&(yy+0>=0)&&(map[xx-1][yy]=='@')) num++;

	if((xx-1>=0)&&(yy+1<B) &&(map[xx-1][yy+1]=='@')) num++;

	if((xx+0>=0)&&(yy-1>=0)&&(map[xx][yy-1]=='@')) num++;

	if((xx+0>=0)&&(yy+1<B) &&(map[xx][yy+1]=='@')) num++;

	if((xx+1<A)&&(yy-1>=0) &&(map[xx+1][yy-1]=='@')) num++;

	if((xx+1<A)&&(yy+0>=0) &&(map[xx+1][yy]=='@')) num++;

	if((xx+1<A)&&(yy+1<B)  &&(map[xx+1][yy+1]=='@')) num++;

	return num;

}

 

//更新地图 

void Open() {

	node c;

	node d;

	while(!dui.empty()) {

		dui.pop();

	}

	c.x=floatx;

	c.y=floaty;

	dui.push(c);

	slect[c.x][c.y]=1;

	while(!dui.empty()) {

		c=dui.front();

		dui.pop();

		if(Boomnum(c.x,c.y)!=0) {

			map[c.x][c.y]=(Boomnum(c.x,c.y)+48);

			continue;

		}

		else {

			map[c.x][c.y]='x';                                                                                                                                                                                                                                                                                                                                                                                                                                     

			if((c.x-1>=0)&&(c.y-1>=0)&&(map[c.x-1][c.y-1]==' ')&&(slect[c.x-1][c.y-1]==0)) {

				d.x=c.x-1;

				d.y=c.y-1;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x-1>=0)&&(c.y-0>=0)&&(map[c.x-1][c.y]==' ')&&(slect[c.x-1][c.y]==0)) {

				d.x=c.x-1;

				d.y=c.y-0;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x-1>=0)&&(c.y+1<B)&&(map[c.x-1][c.y+1]==' ')&&(slect[c.x-1][c.y+1]==0)) {

				d.x=c.x-1;

				d.y=c.y+1;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x-0>=0)&&(c.y-1>=0)&&(map[c.x][c.y-1]==' ')&&(slect[c.x][c.y-1]==0)) {

				d.x=c.x-0;

				d.y=c.y-1;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x-0>=0)&&(c.y+1<B)&&(map[c.x][c.y+1]==' ')&&(slect[c.x][c.y+1]==0)) {

				d.x=c.x-0;

				d.y=c.y+1;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x+1<A)&&(c.y-1>=0)&&(map[c.x+1][c.y-1]==' ')&&(slect[c.x+1][c.y-1]==0)) {

				d.x=c.x+1;

				d.y=c.y-1;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x+1<A)&&(c.y-0>=0)&&(map[c.x+1][c.y]==' ')&&(slect[c.x+1][c.y]==0)) {

				d.x=c.x+1;

				d.y=c.y-0;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

			if((c.x+1<A)&&(c.y+1<B)&&(map[c.x+1][c.y+1]==' ')&&(slect[c.x+1][c.y+1]==0)) {

				d.x=c.x+1;

				d.y=c.y+1;

				dui.push(d);

				slect[d.x][d.y]=1;

			}

		}

	}

}

 

int main() {

	freopen("排名.txt","r",stdin);

	Relife:	//重玩处

	HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);    //获得标准输出设备句柄  

    CONSOLE_SCREEN_BUFFER_INFO csbi;                        //定义窗口缓冲区信息结构体  

    GetConsoleScreenBufferInfo(handle_out, &csbi);          //获得窗口缓冲区信息

    

	Hide();		//隐藏光标

	Beginning();//初始化地图

	a=GetTickCount();

	while(1) {

		if(kbhit()!=0) {

			spare=getch();

			

			//按其他

			if((spare!=(-32))&&(spare!=13)&&(spare!=' ')) continue;//跳过 

			

			//按Enter

			if(spare==13) {	//确认 

				//排雷

				if(mode%2==0) {

					if(map[floatx][floaty]=='@'&&flag[floatx][floaty]==0) {

						break;	//触雷

						game=0;

					}

					

					if(flag[floatx][floaty]==1) continue;	//有旗跳过

					Open();

					position(0,0);

					SetConsoleTextAttribute(handle_out, FORE_GREEN);

					for(int i=0;i<A;i++) {

						for(int j=0;j<B;j++) Lump(i,j);

						printf("\n");

					}

					position(floaty*2,floatx);

					SetConsoleTextAttribute(handle_out, FORE_BLUE);

					Lump(floatx,floaty);

				}

				

				//插拔旗

				else {

					

					//不能插旗的地方

					if(map[floatx][floaty]=='x'||(map[floatx][floaty]>'0'&&map[floatx][floaty]<'9'))

						continue;	//跳过

					

					//插旗

					if(flag[floatx][floaty]==0) {

						flagnum++;

						flag[floatx][floaty]=1;

						position(floaty*2,floatx);

						SetConsoleTextAttribute(handle_out, FORE_BLUE);

						Lump(floatx,floaty);

					}

					

					//拔旗 

					else {

						flagnum--;

						flag[floatx][floaty]=0;

						position(floaty*2,floatx);

						SetConsoleTextAttribute(handle_out, FORE_BLUE);

						Lump(floatx,floaty);

					}

				}

			}

			

			//按空格

			if(spare==' ') Mode();	//切换模式 

			

			//按方向键 

			if(spare==-32) {

				news=getch();

				Move();	//移动光标

			}

			for(int i=0;i<A;i++) for(int j=0;j<B;j++) if(map[i][j]=='x'||(map[i][j]>'0'&&map[i][j]<'9')) game++;

			if(game==A*B-C+1) break;

			else game=1;

			SetConsoleTextAttribute(handle_out, FORE_RED);

			position(44,5);

			printf("剩余雷数:%d ",C-flagnum);

		}

		else Sleep(10);

		b=GetTickCount();

		SetConsoleTextAttribute(handle_out, FORE_RED);

		position(44,7);

		printf("用时:");	//用时 

		if((b-a)/60000<10) printf("0");

		printf("%d:",(b-a)/60000);

		if(((b-a)/1000)%60<10) printf("0");

		printf("%d:",((b-a)/1000)%60);

		if(((b-a)/10)%100<10) printf("0");

		printf("%d",((b-a)/10)%100);

	}

	SetConsoleTextAttribute(handle_out, FORE_RED);

	position(5,5);

	if(game==1) printf("游戏结束!");

	else printf("恭喜通关!");

	position(5,8);

	printf("任意键重玩");

	scanf("%c%c",&spare,&spare);

	system("cls");

	position(0,0);

	goto Relife;

}  

支付宝打赏 微信打赏

您的打赏是对我最大的鼓励!