#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// 简单的猜数字游戏
int main() {
// 初始化随机数生成器
srand(static_cast<unsigned int>(time(0)));
int secretNumber = rand() % 100 + 1; // 生成1到100之间的随机数
int guess;
int attempts = 0;
cout << "欢迎来到猜数字游戏!" << endl;
cout << "我已经想好了一个1到100之间的数字,你能猜出来吗?" << endl;
do {
cout << "请输入你的猜测: ";
cin >> guess;
attempts++;
if (guess > secretNumber) {
cout << "太大了!再试一次。" << endl;
} else if (guess < secretNumber) {
cout << "太小了!再试一次。" << endl;
} else {
cout << "恭喜你,猜对了!" << endl;
cout << "你总共猜了 " << attempts << " 次。" << endl;
}
} while (guess != secretNumber);
return 0;
}
#include <iostream>
用于输入输出流,#include <cstdlib>
和 #include <ctime>
分别用于标准库函数和时间函数。using namespace std;
使我们可以直接使用标准库中的对象和函数,而无需每次都加前缀 std::
。srand(static_cast<unsigned int>(time(0)))
初始化随机数生成器,rand() % 100 + 1
生成一个1到100之间的随机整数。do-while
循环确保用户至少有一次猜测的机会,并且只有在用户猜中时才会退出循环。希望这个简单的猜数字游戏代码对你有帮助!
上一篇:new c++
下一篇:c++ int转char
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站