我正在尝试制作一个简单的猜谜游戏,计算机应该猜测我在 0 到 100 之间选择的数字。尝试运行它,如果数字太低,请按 1,如果数字太高,请按 2。
1.如果我选择50,计算机猜测41,我按1,因为数字太小
2.然后计算机猜测41到100之间,比如说70,我按2,因为它太高了
3.现在的问题是接下来计算机应该猜测70和41之间(之前猜测的数字),但它猜测71和0之间,所以它一直在极端之间上下跳跃
4.我不知道如何让它记住范围,即。之前猜到的数字
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
int num=input.nextInt();
int ans=0;
Random rand = new Random();
int guess=rand.nextInt(100);
while(guess!=num) {
System.out.print("Is it " + guess + " ? ");
ans=input.nextInt();
if (ans==1) {
guess=rand.nextInt(100-guess+1)+guess;
}
else if (ans==2) {
guess=rand.nextInt(100-guess+1)+0;
}
}
System.out.print("Computer guessed: " + guess);
The output looks like this:
Enter a number: 50
Is it 55 ? 2
Is it 26 ? 1
Is it 35 ? 1
Is it 44 ? 1
Is it 54 ? 2
Is it 31 ? 1
Is it 39 ? 1
Is it 87 ? 2
Is it 0 ? 1
Is it 11 ? 1
Is it 97 ? 2
最佳答案
您应该使用 2 个变量:一个用于上限,一个用于下限。
while(guess!=num) {
System.out.print("Is it " + guess + " ? ");
ans=input.nextInt();
if (ans==1) {
lowerLimit = guess; // Your new lower limit .
guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt();
}
else if (ans==2) {
upperLimit = guess; // Your new upper limit.
guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt();
}
}
关于java - 猜谜游戏-如何记住猜谜范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26439274/