
Python
python
import random
def game():
number_to_guess = random.randint(1, 100) wandarealmwuhan.cn
guess = None
attempts = 0
while guess != number_to_guess:
try:
guess = int(input('猜一个1到100之间的数字: '))
attempts += 1
if guess < number_to_guess:
print('太低了!')
elif guess > number_to_guess:
print('太高了!')
except ValueError:
print('请输入一个整数!')
print(f'恭喜你,你猜对了!用了{attempts}次尝试。')
if name == “main”:
game()
JavaScript (在浏览器控制台或Node.js环境中运行)
javascript
function game() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = parseInt(prompt('猜一个1到100之间的数字: '));
attempts++;
if (isNaN(guess)) {
alert('请输入一个整数!');
guess = null;
continue;
}
if (guess < numberToGuess) {
alert('太低了!');
} else if (guess > numberToGuess) {
alert('太高了!');
}
}
alert(`恭喜你,你猜对了!用了${attempts}次尝试。`);
}
game();
C# (控制台应用程序)
csharp
using System;
class Program
{
static void Main()
{
Random rnd = new Random();
int numberToGuess = rnd.Next(1, 101);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess)
{
Console.Write("猜一个1到100之间的数字: ");
bool isNumeric = int.TryParse(Console.ReadLine(), out guess);
if (!isNumeric)
{
Console.WriteLine("请输入一个整数!");
continue;
}
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太低了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太高了!");
}
}
Console.WriteLine($"恭喜你,你猜对了!用了{attempts}次尝试。");
}
}
997

被折叠的 条评论
为什么被折叠?



