c++基础知识点小练习-——猜数字游戏,代码如下:
//c++小练习: // 写一个猜数字游戏 //1.自动产生一个1~100之间的随机数 //2.猜数字 // a.猜对了,就恭喜你,游戏结束 // b.你猜错了,会告诉猜大了,还是猜小了,继续猜,直到猜对 //3.游戏可以一直玩,直到你想退出游戏为止 #include#include #include using namespace std; void menu() { cout << "**************************" << endl; cout << "******* 1. play **********" << endl; cout << "******* 0. exit **********" << endl; cout << "**************************" << endl; } void game()//实现猜数字游戏功能 {//1.生成1~100随机数 int ret = rand()%100+1; //2.猜数字 int guess = 0; while (1)//游戏一直进行,直到猜对为止 { cout << "请猜数字: "; cin >> guess; if (guess < ret) cout << "猜小了" << endl; else if (guess > ret) cout << "猜大了" << endl; else { cout << "恭喜你猜对了!" << endl; break; } } } int main() { int input = 0; srand((unsigned int)time(NULL)); do { menu();//打印菜单 cout << "请选择: "; cin >> input; switch (input) { case 1: cout << "猜数字" << endl; game(); break; case 0: cout << "退出游戏" << endl; break; default: cout << "选择错误,重新选择" << endl; break; } } while (input); return 0; }
代码运行结果:



