C++系统性学习之猜数字游戏
在本篇博客中,我们将学习如何使用C++编写一个程序,实现猜数字游戏的逻辑。
问题描述
我们的任务是编写一个C++程序,接受游戏机产生的随机数和用户的猜测,根据猜测结果输出相应的提示,直到猜对或者超过7次未猜对为止。
解决方
#include <iostream>
using namespace std;
int main() {
// 输入游戏机产生的随机数
int target;
cout << "请输入一个不超过100的正整数,代表游戏机产生的随机数: ";
cin >> target;
// 游戏逻辑
int guess;
int attempts = 0;
while (true) {
cout << "请输入你的猜测: ";
cin >> guess;
attempts++;
if (guess == target) {
cout << "Lucky You!" << endl;
break;
} else if (guess > target) {
cout << "Too big" << endl;
} else {
cout << "Too small" << endl;
}
if (attempts >= 7) {
cout << "Game Over!" << endl;
break;
}
}
return 0;
}