C++ 猜数字游戏代码:简单易懂,新手入门
好的,以下是一个简单的使用 C++ 编写的猜数字小游戏:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
// 生成随机数种子
srand(time(0));
int secretNumber = rand() % 100 + 1; // 生成 1 到 100 之间的随机整数
int guess;
int attempts = 0;
std::cout << '欢迎来到猜数字游戏!\n';
std::cout << '我已经想好了一个 1 到 100 之间的数字,你可以开始猜了!\n';
do {
std::cout << '请输入你的猜测:';
std::cin >> guess;
attempts++;
if (guess > secretNumber) {
std::cout << '猜大了!再试一次\n';
} else if (guess < secretNumber) {
std::cout << '猜小了!再试一次\n';
} else {
std::cout << '恭喜你,猜对了!\n';
std::cout << '你猜了' << attempts << '次。\n';
break;
}
} while (true);
return 0;
}
请注意,这只是一个简单的示例代码,可能还有改进的空间。您可以根据自己的需求进行修改和扩展。享受游戏!
原文地址: https://www.cveoy.top/t/topic/bH1I 著作权归作者所有。请勿转载和采集!