I'm just getting started with C++. I wrote a small program that chooses a random number between 1-100, and then modified it to make the program figure out the number (and count the number of guesses required).
Everything in the program works, except for one thing. I'm using a formula that guesses the difference between the current guess and the previous highest/lowest value, so for a guess that's too low:
low = guess;
guess = (( guess + high ) / 2);
It works great for all numbers except for 100. When it gets to 99, it rounds 199/2 to 99, so I get an endless loop of "99" guesses. Is there a way to prevent this or some formula that would work around this? I know I could make int high = 101 or write a special case if the program is about to guess 99 a second time, but that doesn't seem like the "clean" answer to this.
Thanks!
Complete code of program:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int randResult ( int low, int high )
{
return rand() % ( high - low + 1 ) + low;
}
int main ()
{
srand( time ( NULL ));
int guess = 50; //set the initial guess
int high = 100;
int low = 1;
//int number = randResult( 1, 100 );
int number = 100; //using this to test limits of guessing
int numberOfGuesses = 0;
bool guessCorrectly;
while ( guessCorrectly == 0 )
{
cout << "Computer guessing " << guess << endl;
numberOfGuesses++;
if ( guess == number )
{
cout << "Correct! The number was " << number << endl;
guessCorrectly = 1;
}
else if ( guess < number )
{
cout << "Too low!" << endl;
low = guess;
guess = (( guess + high ) / 2);
}
else
{
cout << "Too high!" << endl;
high = guess;
guess = (( guess + low ) / 2 );
}
}
cout << "Total Number of Guesses: " << numberOfGuesses << endl;
cout << "The Number Was: " << number << endl;
}