I'm trying to learn C++ with the book "Programming Principles and Practice Using C++," and I'm doing an exercise where the computer is supposed to guess a user's number from 1 to 100 in 7 questions. My code almost works, but the computer cannot guess the upper bound (100). How can I fix this? Here's my code.

#include "..\std_lib_facilities_revised.h"

int main()
{
    int low = 1;
    int high = 100;
    int mid = low + (high - low) / 2;
    char response = ' ';
    cout << "Think of a number between 1 and 100.\n";
    while (low < mid) {
        cout << "low: " << low << '\n';
        cout << "high: " << high << '\n';
        cout << "mid: " << mid << '\n';
        cout << "Is your number less than " << mid << "? (y for yes, anything else for no)\n";
        cin >> response;
        if (response == 'y') {
            high = mid;
            mid = low + (high - low) / 2;
        }
        else {
            low = mid;
            mid = low + (high - low) / 2;
        }
    }
    cout << "Your number is: " << low << '\n';
}

1 Answers

4
Nico Schertler On Best Solutions

If your candidate interval contains an even number of entries, you choose the midpoint that is closer to the lower end. Specifically, if you have two numbers a and b, the midpoint will be a. Thus, asking if the number is smaller than the midpoint (a) does not give you any information. You already know that this is not the case.

Instead, you can choose the midpoint to be closer to the upper end:

mid = low + (high - low + 1) / 2;

A second thing you should change is the interval adaptation for the y case. The number is smaller than mid. Hence, the new upper bound should be mid - 1.