- Python
python
import random
def guess_number(): e-energy.cn
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 (在浏览器控制台或Node.js中运行)
javascript
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let 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();
3. Java
Java 通常需要一个完整的类和用户输入/输出处理(例如通过Scanner)。
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;
int attempts = 0;
while (true) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess == numberToGuess) {
System.out.printf("恭喜你,猜对了!你用了%d次尝试。\n", attempts);
break;
} else if (guess < numberToGuess) {
System.out.println("太小了!");
} else {
System.out.println("太大了!");
}
}
scanner.close();
}
}
请注意,这些示例是非常基本的,并且可能不包括错误处理或优化。在实际项目中,您可能还需要添加更多功能,如检查用户输入的有效性等。由于篇幅限制,我将为您提供几种不同编程语言中简单的“猜数字”游戏的基本代码示例。
- 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 (在浏览器控制台或Node.js中运行)
javascript
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let 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();
3. Java
Java 通常需要一个完整的类和用户输入/输出处理(例如通过Scanner)。
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;
int attempts = 0;
while (true) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess == numberToGuess) {
System.out.printf("恭喜你,猜对了!你用了%d次尝试。\n", attempts);
break;
} else if (guess < numberToGuess) {
System.out.println("太小了!");
} else {
System.out.println("太大了!");
}
}
scanner.close();
}
}
请注意,这些示例是非常基本的,并且可能不包括错误处理或优化。在实际项目中,您可能还需要添加更多功能,如检查用户输入的有效性等。