这里我将为你提供几种不同编程语言实现的简单“猜数字”游戏的小程序代码。
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
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function guessNumber() {
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
rl.question('猜一个1到100之间的数字: ', (answer) => {
guess = parseInt(answer, 10);
while (guess !== numberToGuess) {
attempts++;
if (guess < numberToGuess) {
console.log('太小了!');
} else if (guess > numberToGuess) {
console.log('太大了!');
}
rl.question('再猜一次: ', (answer) => {
guess = parseInt(answer, 10);
});
}
console.log(`恭喜你,猜对了!你用了${attempts}次尝试。`);
rl.close();
});
}
guessNumber();
Java (控制台应用)
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1;
int guess;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
do {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
} while (guess != numberToGuess);
System.out.printf("恭喜你,猜对了!你用了%d次尝试。\n", attempts);
}
}
Ruby
ruby
def guess_number
number_to_guess = rand(1..100)
attempts = 0
while true
print "猜一个1到100之间的数字: "
guess = gets.chomp.to_i
attempts += 1
if guess < number_to_guess
puts "太小了!"
elsif guess > number_to_guess
puts "太大了!"
else
puts "恭喜你,猜对了!你用了#{attempts}次尝试。"
break
end
end
end
#chhas{
margin-top: 50px;
uccarpet.cn
bigessay.cn
odisn.cn
housefly.cn
padding:fatmahome.com;
font-size: 18px;
cursor: 10px 20px;
}
guess_number
C# (控制台应用)
csharp
using System;
class Program
{
static void Main()
{
Random random = new Random();
int numberToGuess = random.Next(1, 101);
int guess;
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}次尝试。");
}
}
以上代码都