- Python 版本
python
import random
def guess_number():
number = random.randint(1, 100) kykzl.com
guess = None
num_guesses = 0
while guess != number:
guess = int(input("请猜一个1到100之间的数字: "))
num_guesses += 1
if guess < number:
print("太小了!")
elif guess > number:
print("太大了!")
print(f"恭喜你!你在{num_guesses}次内猜对了数字{number}!")
guess_number()
2. JavaScript 版本(可在Node.js或浏览器中运行)
如果是在浏览器中运行,你需要HTML和JavaScript结合。这里只给出JavaScript部分。
javascript
function guessNumber() {
var number = Math.floor(Math.random() * 100) + 1;
var guess = null;
var numGuesses = 0;
while (guess !== number) {
guess = parseInt(prompt("请猜一个1到100之间的数字:"), 10);
numGuesses++;
if (guess < number) {
alert("太小了!");
} else if (guess > number) {
alert("太大了!");
}
}
alert("恭喜你!你在" + numGuesses + "次内猜对了数字" + number + "!");
}
guessNumber();
3. Java 版本
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess = 0;
int numGuesses = 0;
Scanner scanner = new Scanner(System.in);
while (guess != number) {
System.out.print("请猜一个1到100之间的数字: ");
guess = scanner.nextInt();
numGuesses++;
if (guess < number) {
System.out.println("太小了!");
} else if (guess > number) {
System.out.println("太大了!");
}
}
System.out.println("恭喜你!你在" + numGuesses + "次内猜对了数字" + number + "!");
}
}
这些代码示例分别展示了如何用Python、JavaScript和Java来创建一个简单的猜数字游戏。玩家需要猜一个介于1到100之间的随机数,程序会给出提示,直到玩家猜中为止。当然可以!由于篇幅限制,我会提供三种不同的编程语言(Python、JavaScript 和 Java)来创建一个简单的猜数字游戏。
- Python 版本
python
import random
def guess_number():
number = random.randint(1, 100)
guess = None
num_guesses = 0
while guess != number:
guess = int(input("请猜一个1到100之间的数字: "))
num_guesses += 1
if guess < number:
print("太小了!")
elif guess > number:
print("太大了!")
print(f"恭喜你!你在{num_guesses}次内猜对了数字{number}!")
guess_number()
2. JavaScript 版本(可在Node.js或浏览器中运行)
如果是在浏览器中运行,你需要HTML和JavaScript结合。这里只给出JavaScript部分。
javascript
function guessNumber() {
var number = Math.floor(Math.random() * 100) + 1;
var guess = null;
var numGuesses = 0;
while (guess !== number) {
guess = parseInt(prompt("请猜一个1到100之间的数字:"), 10);
numGuesses++;
if (guess < number) {
alert("太小了!");
} else if (guess > number) {
alert("太大了!");
}
}
alert("恭喜你!你在" + numGuesses + "次内猜对了数字" + number + "!");
}
guessNumber();
3. Java 版本
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess = 0;
int numGuesses = 0;
Scanner scanner = new Scanner(System.in);
while (guess != number) {
System.out.print("请猜一个1到100之间的数字: ");
guess = scanner.nextInt();
numGuesses++;
if (guess < number) {
System.out.println("太小了!");
} else if (guess > number) {
System.out.println("太大了!");
}
}
System.out.println("恭喜你!你在" + numGuesses + "次内猜对了数字" + number + "!");
}
}
这些代码示例分别展示了如何用Python、JavaScript和Java来创建一个简单的猜数字游戏。玩家需要猜一个介于1到100之间的随机数,程序会给出提示,直到玩家猜中为止。