- Python
python
import random
def guess_number():
number_to_guess = random.randint(1, 100) siguansheji.com
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()
2. JavaScript (在浏览器控制台或HTML文件中运行)
html
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
int guess = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
} while (guess != numberToGuess);
System.out.println("恭喜你,猜对了! 用了" + attempts + "次尝试。");
}
}
以上代码示例展示了如何使用不同编程语言实现一个简单的“猜数字”游戏。您可以根据自己的需要进行修改和扩展。由于篇幅限制,我将为您提供几种不同编程语言中简单的“猜数字”游戏的基本代码示例。
- 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()
2. JavaScript (在浏览器控制台或HTML文件中运行)
html
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
int guess = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
} while (guess != numberToGuess);
System.out.println("恭喜你,猜对了! 用了" + attempts + "次尝试。");
}
}
以上代码示例展示了如何使用不同编程语言实现一个简单的“猜数字”游戏。您可以根据自己的需要进行修改和扩展。