c++语言小游戏代码简单
时间: 2023-07-09 17:12:56 浏览: 103
这是一个经典的猜数字小游戏的C++代码示例:
```c++
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int guess, number, attempts = 0;
srand(time(0)); // 随机数种子
number = rand() % 100 + 1; // 随机生成1-100之间的数字
cout << "我想了一个1-100之间的数字,你来猜猜看吧!" << endl;
do {
attempts++;
cout << "请输入你猜测的数字:" << endl;
cin >> guess;
if (guess > number) {
cout << "太大了,再猜一次!" << endl;
}
else if (guess < number) {
cout << "太小了,再猜一次!" << endl;
}
else {
cout << "恭喜你,猜对了!" << endl;
cout << "你猜了 " << attempts << " 次。" << endl;
}
} while (guess != number);
return 0;
}
```
运行后,程序会随机生成一个1-100之间的数字,然后要求用户输入一个数字进行猜测。如果猜测的数字与生成的数字相同,程序会提示用户猜对了,并输出用户猜测的次数;如果猜测的数字比生成的数字大或者小,程序会提示用户再次猜测,直到猜对为止。