Python 版本
python
import random
def guess_number(): sidaotech.com
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input('猜一个1到100之间的数字: '))
attempts += 1
if guess < number_to_guess:
print('太小了!')
elif guess > number_to_guess:
print('太大了!')
print(f'恭喜你,猜对了!你用了{attempts}次尝试。')
if name == “main”:
guess_number()
JavaScript 版本(在浏览器控制台或Node.js环境中运行)
javascript
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = parseInt(prompt('猜一个1到100之间的数字: '));
attempts++;
if (guess < numberToGuess) {
console.log('太小了!');
} else if (guess > numberToGuess) {
console.log('太大了!');
}
}
console.log(`恭喜你,猜对了!你用了${attempts}次尝试。`);
}
guessNumber();
C# 版本(控制台应用程序)
csharp
using System;
class Program
{
static void Main()
{
GuessNumber();
}
static void GuessNumber()
{
Random rnd = new Random();
int numberToGuess = rnd.Next(1, 101);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess)
{
Console.Write("猜一个1到100之间的数字: ");
if (int.TryParse(Console.ReadLine(), out guess))
{
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
}
else
{
Console.WriteLine("输入无效,请输入一个整数。");
}
}
Console.WriteLine($"恭喜你,猜对了!你用了{attempts}次尝试。");
}
}
以上三个程序都是“猜数字”游戏的简单实现,它们会随机生成一个1到100之间的数字,然后让用户来猜,直到猜对为止。由于不同电脑语言(编程语言)具有不同的特性和用途,以下我将分别用Python(一种通用编程语言)、JavaScript(常用于网页和前端开发)和C#(常用于.NET框架和Unity游戏开发)来编写一个简单的“猜数字”游戏。
Python 版本
python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input('猜一个1到100之间的数字: '))
attempts += 1
if guess < number_to_guess:
print('太小了!')
elif guess > number_to_guess:
print('太大了!')
print(f'恭喜你,猜对了!你用了{attempts}次尝试。')
if name == “main”:
guess_number()
JavaScript 版本(在浏览器控制台或Node.js环境中运行)
javascript
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = parseInt(prompt('猜一个1到100之间的数字: '));
attempts++;
if (guess < numberToGuess) {
console.log('太小了!');
} else if (guess > numberToGuess) {
console.log('太大了!');
}
}
console.log(`恭喜你,猜对了!你用了${attempts}次尝试。`);
}
guessNumber();
C# 版本(控制台应用程序)
csharp
using System;
class Program
{
static void Main()
{
GuessNumber();
}
static void GuessNumber()
{
Random rnd = new Random();
int numberToGuess = rnd.Next(1, 101);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess)
{
Console.Write("猜一个1到100之间的数字: ");
if (int.TryParse(Console.ReadLine(), out guess))
{
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
}
else
{
Console.WriteLine("输入无效,请输入一个整数。");
}
}
Console.WriteLine($"恭喜你,猜对了!你用了{attempts}次尝试。");
}
}
以上三个程序都是“猜数字”游戏的简单实现,它们会随机生成一个1到100之间的数字,然后让用户来猜,直到猜对为止。