Search code examples
c++logarithm

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


I found that in order to allow the guesser to guess 100, I need to set the maximum value to 100. I am confused by this, since if something is maximum 100, doesn't that include 100? Is there something wrong with my code? Can anyone explain? Noob here looking for some help. Thanks so much! Here is the code:

#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;
}

Solution

  • That would be because of integer truncation.

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

    Work this out for large numbers, such that max = 100 and min = 50, and we get:

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

    Now, if this guess is wrong, and we keep going higher, then this happens:

    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
    

    And there's your problem. If you just save the result directly into an int, the decimal component will be cut off entirely, instead of being rounded. If you just want a quick-and-dirty fix, you could have it check for another special case.

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

    I believe that should work.


    Edit: Darn, StillLearning beat me to it.