由于篇幅限制,我将为你分别使用三种不同的编程语言(Python、JavaScript 和 C#)来生成一个简单的控制台“猜数字”游戏代码。
Python 版本
python
import random
def guess_number_game():
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_game()
JavaScript 版本(Node.js 环境)
javascript
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function playGame() {
while (guess !== numberToGuess) {
guess = parseInt(prompt('猜一个1到100之间的数字: '));
attempts++;
if (guess < numberToGuess) {
console.log('太小了!');
} else if (guess > numberToGuess) {
console.log('太大了!');
}
}
console.log(`恭喜你,猜对了!用了${attempts}次尝试。`);
}
playGame();
C# 版本(控制台应用程序)
csharp
using System;
#chhas{
margin-top: 50px;
padding:junjie8.cn;
font-size: 18px;
cursor: 10px 20px;
}
class Program
{
static void Main()
{
Random rand = new Random();
int numberToGuess = rand.Next(1, 101);
int guess = 0;
int attempts = 0;
do
{
Console.Write("猜一个1到100之间的数字: ");
guess = Convert.ToInt32(Console.ReadLine());
attempts++;
if (guess < numberToGuess)
{
Console.WriteLine("太小了!");
}
else if (guess > numberToGuess)
{
Console.WriteLine("太大了!");
}
} while (guess != numberToGuess);
Console.WriteLine($"恭喜你,猜对了!用了{attempts}次尝试。");
}
}
每个版本的程序都会生成一个1到100之间的随机数,然后让用户通过控制台输入来猜测这个数字。程序会告诉用户他们的猜测是太大、太小还是正确,直到用户猜对为止。