I have a program that generates a number between 1 and 100 and then has it guess what number it is. Its first guess is always 50, then it does something different if it's lower or higher than the real number. I'm looking for an optimal solution to having it guess the number when 50 is too low. Right now, all I have the program do is increment 50 until it gets to the right number. Also, I would like some critique for the code I wrote when 50 is too high of a number.
# include <ctime>
# include <cstdlib>
# include <iostream>
usingnamespace std;
//Random number function
int randRange (int low, int high)
{
return rand() % (high - low + 1) + low;
}
int main()
{
srand(time(NULL));
//Random number is generated between 1 and 100
int number=randRange(1,100);
//First guess is always 50
int guessNumber=50;
//Guess attempts are counted from zero
int guessAttempts=0;
cout << "Guess what number I'm thinking of...it's between 1 and 100 (inclusive)." << '\n';
cout << guessNumber << '\n';
guessAttempts++;
while (number != guessNumber)
{ // if number is higher than what was guessed,
//the guess is simply incremented until it gets
//to the right number
if (number > guessNumber)
{
cout << "Too low..." << '\n';
guessNumber = guessNumber++;
cout << guessNumber << '\n';
guessAttempts++;
}
// if number is less than what was guessed, the guess
//is divided in twos until it's too low, then it just
//takes the average number between the higher and lower numbers
elseif (number < guessNumber)
{
cout << "Too high..." << '\n';
guessNumber = guessNumber / 2;
cout << guessNumber << '\n';
guessAttempts++;
if (number > guessNumber)
{
cout << "Too low..." << '\n';
int guessNumber2 = guessNumber * 2;
guessNumber = (guessNumber + guessNumber2) / 2;
cout << guessNumber << '\n';
guessAttempts++;
}
}
}
cout << "Correct!" << '\n';
cout << "Number should be: " << number << '\n';
cout << "# of guesses: " << guessAttempts << '\n';
}
https://en.wikipedia.org/wiki/Bisection_method
You need to keep track of where you are. If always in the lower interval, you divide by 2. If you get too low, you need to know your upper limit, and divide that interval by 2. So if I am thinking of 82, the first guess is 50, then 75, then 87, then 81, then 84, and finally 82