所以我做了这个游戏,我选择了一个1-100的随机数,计算机猜测我告诉它太高,太低,或者其他什么。它工作得很好,除了当我尝试二进制搜索时它被卡在循环中,我似乎无法阻止它。我将演示:
说数字为79.最后,程序会询问该数字是否为42.不,这个数字太低了。然后问它是否是71.猜得更高!然后它问82.不,低。然后它回到42并且循环一遍又一遍地重复。这是我的代码(请注意,它是完整代码的摘录,因此缺少输入JOptionPane等等):
int x = 50;
int y = x;
int[] alreadyGuessed = {};
boolean secondGuess = false;
//The user has to select, too high, too low, correct!
while (secondGuess == false) {
Object[] options = {"Too high", "Too Low", "Correct"};
int pick = JOptionPane.showOptionDialog(null, "Is your number " + x
+ "?", "Guess",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[2]);
for (int positionInList = 0; positionInList >= 100; positionInList++) {
arrayDemo(x, positionInList);
}
if (pick == 0) {
int max = x - 1;
int min = 0;
x = ((max + min) / 2);
}
if (pick == 1) {
int max = 100;
int min = x+1;
x = ((max + min) / 2);
}
if (pick == 2) {
System.out.println("Yay! I win!");
secondGuess = true;
}
}
答案 0 :(得分:1)
您需要跟踪最小值和最大值。因此,在您的代码中,当您说max = 100
或min = 0
时,该程序会忘记最大值和最大值。分钟。
删除这些行&你应该没事。从本质上讲,你需要记住min&一直到最大,直到找到答案。
e.g。如果数字是42,则min和max将如下:
0..100, guess 50 (too high)
0..49, guess 25 (too low)
26..49, guess 38 (too low)
39..49, guess 44 (too high)
39..43, guess 41 (too low)
42..43, guess 42 WIN!
注意min和max如何放大答案。提供这些信息是使战略发挥作用的原因。