我正在尝试创建一个游戏,其中AI会通过一系列问题来猜测用户正在思考的数字。
例:
Is your number greater than 50? (y/n)
n
Is your number greater than 25? (y/n)
y
Is your number greater than 38? (y/n)
y
Is your number greater than 44? (y/n)
n
Is your number greater than 41? (y/n)
y
Is your number greater than 43? (y/n)
y
The number you're thinking of is 44.
我了解您必须根据用户输入的内容设置新的upperLimit和lowerLimit,然后返回新限制的平均值。我的代码运行不正常。
如果我想到数字59,我的代码会做什么。
Is your number greater than 50? (y/n)
y
Is your number greater than 75? (y/n)
n
Is your number greater than 62? (y/n)
n
Is your number greater than 56? (y/n)
y
Is your number greater than 59? (y/n)
n
Is your number greater than 57? (y/n)
y
Is your number greater than 58? (y/n)
y
Is your number greater than 58? (y/n)
y
Is your number greater than 58? (y/n)
y
Is your number greater than 58? (y/n)
y
Is your number greater than 58? (y/n)
任何建议/技巧/帮助将不胜感激!
我的代码:
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
while (lowerLimit != upperLimit) {
if(isGreaterThan(average(lowerLimit, upperLimit))) {
lowerLimit = average(lowerLimit, upperLimit);
} else {
upperLimit = average(lowerLimit, upperLimit);
}
}
System.out.println("The number you're thinking of is " + lowerLimit);
}
public boolean isGreaterThan(int value) {
System.out.println("Is your number greater than " + value + "? (y/n)");
String answer = reader.nextLine();
return answer.equals("y");
}
public int average(int firstNumber, int secondNumber) {
return (firstNumber + secondNumber) / 2;
}
最佳答案
试试这个lowerLimit = average(lowerLimit,upperLimit)+ 1;
解释很简单。您一直在问的问题是数字是否大于X。如果是,则X + 1应该成为下限,因为显然数字不能为X。另一端不能应用相同的数字。间隔,因为如果您的数字是X,则问题的答案是否更大是否,因此upperLimit应该保持X。