Python
python
import random
def guess_number():
number_to_guess = random.randint(1, 100) cnavmall.cn
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}次尝试。')
guess_number()
JavaScript (在浏览器控制台或Node.js环境中运行)
javascript
function guessNumber() {
var numberToGuess = Math.floor(Math.random() * 100) + 1;
var guess = null;
var 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()
{
Random rnd = new Random();
int numberToGuess = rnd.Next(1, 101);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess)
{
Console.Write("猜一个1到100之间的数字: ");
guess = int.Parse(Console.ReadLine());
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
}
Console.WriteLine($"恭喜你,你猜对了!用了{attempts}次尝试。");
}
}
这些代码示例都是“猜数字”游戏的简单实现,其中程序随机选择一个1到100之间的数字,然后让用户尝试猜测这个数字。程序会告诉用户他们的猜测是太大、太小还是正确,并计算用户尝试的次数。由于篇幅限制,我无法为每种编程语言都提供一个完整的小游戏代码,但我可以为几种常见的编程语言(如Python、JavaScript和C#)提供简单的“猜数字”游戏的代码示例。
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}次尝试。')
guess_number()
JavaScript (在浏览器控制台或Node.js环境中运行)
javascript
function guessNumber() {
var numberToGuess = Math.floor(Math.random() * 100) + 1;
var guess = null;
var 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()
{
Random rnd = new Random();
int numberToGuess = rnd.Next(1, 101);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess)
{
Console.Write("猜一个1到100之间的数字: ");
guess = int.Parse(Console.ReadLine());
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
}
Console.WriteLine($"恭喜你,你猜对了!用了{attempts}次尝试。");
}
}
这些代码示例都是“猜数字”游戏的简单实现,其中程序随机选择一个1到100之间的数字,然后让用户尝试猜测这个数字。程序会告诉用户他们的猜测是太大、太小还是正确,并计算用户尝试的次数。