为什么我需要将最大值设置为 101 才能让我的基本猜测程序猜测 100?

Why do I need to set the max value to 101 in order for my basic guessing program to guess 100?

我发现为了让猜的人猜到100,我需要设置最大值为100。我对此感到困惑,因为如果某些东西是最大值 100,那不包括 100 吗?我的代码有问题吗?谁能解释一下?菜鸟在这里寻求帮助。非常感谢! 这是代码:

#include <iostream>
using namespace std;

char yes_or_no;
int guess = 0;

void guesser(int we_are_on, int max, int min)
{
  cin >> yes_or_no;
  if (yes_or_no == 'y')
    max = we_are_on;
  else if (yes_or_no == 'n')
    min = we_are_on;
  else
    cout << "Bad Input!\n";
  cout << "Max: " << max << " Min: " << min << " Running Guess: " << we_are_on;
  we_are_on = min + ((max-min) / 2);
  cout << "\nIs your number less than " << we_are_on << '?';
  if (max - min <= 1)
  {
    guess = we_are_on;
    return;
  }
  guesser(we_are_on, max, min);
}

int main() 
{
  cout << "Is your number less than 50?";
  guesser(50, 101, 1);
  cout << "\n Your number is " << guess;
  return 0;
}

考虑 max = 100min=99

然后这一行

we_are_on= min + ((max-min)/2 );

we_are_on= 99 + ((100-99)/2 ) = 99 + (1/2) = 99 + 0 = 99

所以你不能达到 100。

问题是整数除法的结果总是被截断。

如果要对整数除法进行四舍五入,则必须在先除以的数字上加上一半。

示例:

int x = 16;
int y = 10;  // must be an equal number in this example
int z = x/y; // z is 1 due to truncation
int w = (x + y/2)/y; // add y/2 before division with y => w is 2, i.e. rounding

那是因为整数截断。

we_are_on= min + ((max-min)/2 );

计算大数,例如 max = 100min = 50,我们得到:

we_are_on= 50 + ((max-min)/2 );
         = 50 + ((100 - 50)/ 2);
         = 75

现在,如果这个猜测是错误的,并且我们继续走高,那么会发生这种情况:

guesser(75, 100, 1);
we_are_on= 75 + ((100-75)/2 );
         = (int) 87.5
         = 87

guesser(87, 100, 1);
we_are_on= 87 + ((100-87)/2 );
         = (int) 93.5
         = 93

guesser(93, 100, 1);
we_are_on= 93 + ((100-93)/2 );
         = (int) 96.5
         = 96

guesser(96, 100, 1);
we_are_on= 96 + ((100-96)/2 );
         = 98

guesser(98, 100, 1);
we_are_on= 98 + ((100-98)/2 );
         = 99

guesser(99, 100, 1);
we_are_on= 99 + ((100-99)/2 );
         = (int) 99.5
         = 99
// And therefore...
guesser(99, 100, 1); // ad infinitum

这就是你的问题。如果直接将结果保存到 int 中,小数部分将被完全切掉,而不是四舍五入。如果您只想 quick-and-dirty 修复,您可以让它检查另一个特殊情况。

if (min == 99) {
    guess = 100;
} else if (max - min <= 1) {
    guess = we_are_on;
} else {
    guesser(we_are_on, max, min);
}

我相信这应该有效。


编辑:该死,StillLearning 抢在我前面。