c++猜数字游戏
2026-03-18 16:40:47
发布于:浙江
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
// 初始化随机数种子
srand(time(0));
// 生成1到100之间的随机数
int target = rand() % 100 + 1;
int guess;
int attempts = 0;
cout << "欢迎来到猜数字游戏!" << endl;
cout << "我已经想好了一个1到100之间的数字,你可以无限次尝试来猜中它。" << endl;
cout << "输入 '0' 可以退出游戏。" << endl;
while(true) {
cout << "\n请输入你的猜测: ";
if (!(cin >> guess)) {
cout << "请输入一个有效的数字!" << endl;
cin.clear();
cin.ignore(10000, '\n');
continue;
}
// 检查是否退出游戏
if (guess == 0) {
cout << "感谢游玩!正确答案是 " << target << "。" << endl;
break;
}
attempts++;
if (guess == target) {
cout << "恭喜你!猜对了!答案就是 " << target << "。" << endl;
cout << "你总共用了 " << attempts << " 次就猜中了!" << endl;
break;
} else if (guess < target) {
cout << "太小了!试试更大的数字。";
} else {
cout << "太大了!试试更小的数字。";
}
}
return 0;
}
这里空空如也



















有帮助,赞一个