如何缩小数字以猜测数字程序中的逻辑错误

时间:2018-12-21 00:51:11

标签: java loops numbers

我目前正在从事“猜数字”项目。提示要求用户考虑一个介于1到1000之间的数字(包括1到1000)。我的问题是“较高”和“较低”条件背后的逻辑。

我尝试了很多组合,但是我的代码仍然与输入代码不匹配。我有点理解为什么,但是我不能把它放在一起,为什么它不能缩小我的数字。

String text;
int min = 1;
int max = 1000;
int guess = 500;
int guess1, guess2;

while (!text.equals("yes")){
  System.out.println("Is your number " + (guess) + "?");
  System.out.println("yes,higher,or lower");
  text = reader.nextLine();
  if (text.equals("higher")){
    min = guess;
    guess1 = ((max - min+1)/2);
    guess = guess1 + min;
  }
  if (text.equals("lower")){
    min = guess;
    guess = (max - min)/2;
  }
}
}
}

我目前正在尝试猜测300。这是我的输出:    Is your number 500? yes,higher,or lower lower Is your number 250? yes,higher,or lower higher Is your number 625? yes,higher,or lower lower Is your number 187? yes,higher,or lower higher Is your number 594? yes,higher,or lower lower Is your number 203? yes,higher,or lower 这是所需的输出:

Is your number 500?
yes, higher, or lower
 lower
 Is your number 250?
 yes, higher, or lower
 higher
Is your number 375?
yes, higher, or lower
 lower
 Is your number 312?
 yes, higher, or lower
 lower
 Is your number 281?
 yes, higher, or lower
 higher
 Is your number 296?
 yes, higher, or lower
 higher
  Is your number 304?
  yes, higher, or lower
  lower
 Is your number 300?
 yes, higher, or lower
  yes

2 个答案:

答案 0 :(得分:0)

您没有正确设置minmax

lower情况下,由于您已经淘汰了max,因此要将guess - 1设置为guess。另外,通过将新的guessmax相加而不是相减,将其设置为minupper的平均值。

guess1情况下,您不需要变量min。既然已经消除了guess + 1,只需将guess设置为guess,然后再次将max设置为minif (text.equals("higher")){ min = guess + 1; guess = (max + min)/2; } if (text.equals("lower")){ max = guess - 1; guess = (max + min)/2; } 的平均值。 / p>

const [data, setData] = useState(null)

答案 1 :(得分:0)

您永远不会更新max变量,但是您正在使用它来计算猜测值。 我会建议,像这样。

while (!text.equals("yes")) {
        System.out.println("Is your number " + (guess) + "?");
        System.out.println("yes,higher,or lower");
        text = reader.nextLine();

        if (text.equals("higher")) {
            min = guess;
        }
        if (text.equals("lower")) {
            max = guess;
        }
        guess = (max + min) / 2;
    }