Python 版本
python
import random
def guess_number_game(): hongjet.cn
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
print("猜猜看,我心里想的是哪个1到100之间的数字?")
while guess != number_to_guess:
try:
guess = int(input("请输入你的猜测:"))
attempts += 1
if guess < number_to_guess:
print("太小了!")
elif guess > number_to_guess:
print("太大了!")
else:
print(f"恭喜你,猜对了!数字就是{number_to_guess}。你总共猜了{attempts}次。")
except ValueError:
print("请输入一个有效的数字。")
guess_number_game()
JavaScript 版本(在浏览器中运行)
html
猜数字游戏
我心里想了一个1到100之间的数字,你能猜到是多少吗?
提交 C++ 版本 C++ 标准库中没有直接的 GUI 支持,但我们可以使用控制台来模拟这个游戏。cpp
#include
#include // 用于rand()和srand()
#include // 用于time()
using namespace std;
int main() {
srand(time(0)); // 初始化随机数生成器
int numberToGuess = rand() % 100 + 1;
int guess;
int attempts = 0;
cout << "猜猜看,我心里想的是哪个1到100之间的数字?" << endl;
while (true) {
cin >> guess;
attempts++;
if (cin.fail()) {
cin.clear(); // 清除错误状态
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 忽略错误输入
cout << "请输入一个有效的数字。" << endl;
continue;
}
if (guess < numberToGuess) {
cout << "太小了!" << endl;
} else if (guess > numberToGuess) {
cout << "太大了!" << endl;
} else {
cout << "恭喜你,猜对了!数字就是" << numberToGuess << "。你总共猜了" << attempts << "次。" << endl;
break;
}
}
return 0;
}
每个示例都展示了一个基本的猜数字游戏,但它们的实现方式根据所使用的编程语言和环境的不同而有所差异。由于直接在一个回答中展示多种编程语言编写的完整小游戏可能过于冗长,我将分别用几种流行的编程语言(Python、JavaScript、C++)概述一个简单的猜数字游戏的基本框架。这个游戏会让用户尝试猜测一个程序随机生成的1到100之间的数字。
Python 版本
python
import random
def guess_number_game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
print("猜猜看,我心里想的是哪个1到100之间的数字?")
while guess != number_to_guess:
try:
guess = int(input("请输入你的猜测:"))
attempts += 1
if guess < number_to_guess:
print("太小了!")
elif guess > number_to_guess:
print("太大了!")
else:
print(f"恭喜你,猜对了!数字就是{number_to_guess}。你总共猜了{attempts}次。")
except ValueError:
print("请输入一个有效的数字。")
guess_number_game()
JavaScript 版本(在浏览器中运行)
html
猜数字游戏
我心里想了一个1到100之间的数字,你能猜到是多少吗?
提交 C++ 版本 C++ 标准库中没有直接的 GUI 支持,但我们可以使用控制台来模拟这个游戏。cpp
#include
#include // 用于rand()和srand()
#include // 用于time()
using namespace std;
int main() {
srand(time(0)); // 初始化随机数生成器
int numberToGuess = rand() % 100 + 1;
int guess;
int attempts = 0;
cout << "猜猜看,我心里想的是哪个1到100之间的数字?" << endl;
while (true) {
cin >> guess;
attempts++;
if (cin.fail()) {
cin.clear(); // 清除错误状态
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 忽略错误输入
cout << "请输入一个有效的数字。" << endl;
continue;
}
if (guess < numberToGuess) {
cout << "太小了!" << endl;
} else if (guess > numberToGuess) {
cout << "太大了!" << endl;
} else {
cout << "恭喜你,猜对了!数字就是" << numberToGuess << "。你总共猜了" << attempts << "次。" << endl;
break;
}
}
return 0;
}
每个示例都展示了一个基本的猜数字游戏,但它们的实现方式根据所使用的编程语言和环境的不同而有所差异。