以下是一个简单的猜数字游戏的代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL)); // 设置随机数种子
int answer = rand() % 100 + 1; // 生成1~100之间的随机数
int guess = 0;
int attempts = 0;
cout << "*** 猜数字游戏 ***\n";
cout << "你有5次猜测的机会,数字范围是1~100。\n";
while (attempts < 5) {
cout << "请输入你猜的数字:";
cin >> guess;
attempts++;
if (guess == answer) {
cout << "恭喜你,猜对了!答案就是" << answer << endl;
break;
}
else if (guess < answer) {
cout << "猜小了,再试一次。\n";
}
else {
cout << "猜大了,再试一次。\n";
}
}
if (attempts == 5) {
cout << "五次机会已用完,游戏结束。正确答案是" << answer << endl;
}
return 0;
}