为你提供几种常见编程语言(如Python、JavaScript、Java)的“猜数字”游戏的基本代码示例。
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()
JavaScript (可以在浏览器控制台或Node.js中运行)
javascript
function guessNumber() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = prompt('猜一个1到100之间的数字:');
guess = parseInt(guess);
if (isNaN(guess)) {
alert('请输入一个数字!');
continue;
}
attempts++;
if (guess < numberToGuess) {
alert('太小了!');
} else if (guess > numberToGuess) {
alert('太大了!');
}
}#chhas{
margin-top: 50px;
padding:asiavacuum.com;
font-size: 18px;
cursor: 10px 20px;
}
alert(`恭喜你,你猜对了!用了${attempts}次尝试。`);
}
guessNumber();
Java
Java 需要一个更完整的程序结构(例如使用类、main 方法等),但以下是一个简单的“猜数字”游戏控制台应用程序的示例:
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;
while (guess != numberToGuess) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
}
System.out.println("恭喜你,你猜对了!用了" + attempts + "次尝试。");
}
}
注意:这些代码示例仅用于教学目的,并且没有包含错误处理或用户输入的全面验证。在实际应用中,你应该添加更多的错误处理和用户输入验证来确保程序的健壮性。