随便写一个c++小游戏的代码
时间: 2023-08-13 21:53:09 浏览: 44
好的,以下是一个简单的猜数字游戏的C++代码示例:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(nullptr)); // 随机数种子初始化
int secretNumber = rand() % 100 + 1; // 生成1到100之间的随机数
int guess;
int tries = 0;
cout << "欢迎来到猜数字游戏!" << endl;
do {
cout << "请输入一个猜测的数字(1-100): ";
cin >> guess;
tries++;
if (guess > secretNumber) {
cout << "太大了!请再试一次。" << endl;
} else if (guess < secretNumber) {
cout << "太小了!请再试一次。" << endl;
} else {
cout << "恭喜你猜对了!" << endl;
cout << "你猜了 " << tries << " 次。" << endl;
}
} while (guess != secretNumber);
return 0;
}
```
这个游戏会生成一个1到100之间的随机数,然后玩家需要通过输入数字来猜测这个随机数是多少。游戏会根据玩家的猜测给出相应的提示,直到玩家猜对为止。程序会统计玩家猜测的次数,并在猜对时显示出来。