当涉及到多种电脑语言时,我可以为您提供一个简单的“猜数字”游戏示例,但请注意,每种语言的环境和用途可能略有不同。以下是使用Python、JavaScript(Node.js 环境)、Java和C#编写的示例代码。
Python
python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
attempts = 0
guess = None
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').createInterface({
input: process.stdin,
output: process.stdout
}); #chhas{
margin-top: 50px;
padding:ns66.cn;
font-size: 18px;
cursor: 10px 20px;
}
function guessNumber() {
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
readline.question('猜一个1到100之间的数字: ', (answer) => {
guess = parseInt(answer, 10);
while (guess !== numberToGuess) {
attempts++;
if (guess < numberToGuess) {
readline.write('太小了!\n');
} else if (guess > numberToGuess) {
readline.write('太大了!\n');
}
readline.question('再猜一次: ', (answer) => {
guess = parseInt(answer, 10);
});
}
readline.close();
console.log(`恭喜你,猜对了!你用了${attempts}次尝试。`);
});
}
guessNumber();
Java
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
int guess = 0;
int attempts = 0;
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);
}
}
C#
csharp
using System;
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 = int.Parse(Console.ReadLine());
attempts++;
if (guess < numberToGuess) {
Console.WriteLine("太小了!");
} else if (guess > numberToGuess) {
Console.WriteLine("太大了!");
}
} while (guess != numberToGuess);
Console.WriteLine($"恭喜你,猜对了!你用了{attempts}次尝试。");
}
}
这些示例都实现了相同的“猜数字”游戏逻辑,但在不同的编程环境中运行。请注意,JavaScript 的 Node.js 示例使用了 readline 模块来从命令行读取输入,这与其他语言中的标准输入/输出方法略有不同。