#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;
while (true) {
cout << "\n请输入你的猜测:";
cin >> guess;
attempts++;
// 输入校验
if (cin.fail() || guess < 1 || guess > 100) {
cin.clear(); // 清除错误状态
cin.ignore(1000, '\n'); // 清空输入缓冲区
cout << "输入无效!请输入1-100之间的整数!";
continue;
}
// 核心判断逻辑
if (guess > target) {
cout << "猜大了!再试试~";
} else if (guess < target) {
cout << "猜小了!再试试~";
} else {
cout << "\n?? 恭喜你猜对了!??" << endl;
cout << "你一共猜了 " << attempts << " 次!" << endl;
break;
}
}
return 0;
}