请用C++写一个猜数字游戏
时间: 2023-12-27 10:44:17 浏览: 26
好的,请看下面的代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // 设置随机数种子,确保每次运行程序时生成的随机数不同
int number = rand() % 100 + 1; // 生成 1~100 之间的随机整数
int guess;
cout << "我想了一个 1~100 之间的数字,你猜是多少?" << endl;
do {
cout << "请输入你猜的数字:";
cin >> guess;
if (guess < number) {
cout << "你猜的数字太小了,再试试!" << endl;
} else if (guess > number) {
cout << "你猜的数字太大了,再试试!" << endl;
} else {
cout << "恭喜你,猜对了!你真聪明!" << endl;
}
} while (guess != number);
return 0;
}
```
这是一个简单的猜数字游戏,程序会生成一个 1~100 之间的随机整数,然后让玩家猜这个数字是多少。如果猜的数字太小了,程序会提示“你猜的数字太小了,再试试!”;如果猜的数字太大了,程序会提示“你猜的数字太大了,再试试!”;如果猜对了,程序会提示“恭喜你,猜对了!你真聪明!”