问题
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;
}
回答1:
Another alternative is that you start with
int high= 101 ;
You are never going to ask for 101
, because in the worst case you will have
low= 99 ;
high= 101 ;
And then
guess= ( low + high ) / 2 ; // = 100
回答2:
Try
low = guess;
guess = (( guess + high +1) / 2);
回答3:
well the problem with your code is obvious:
else if(guess<number)
{
low=guess;
}
The problem here is that you are assigning lower limit to the number guessed but this is not logical since guess is lower that the number so use instead:
low=guess+1;
This code not only solves the problem but also lowers the execution time since there will be less number to be checked similarly:
else
{
high=guess-1;
}
来源:https://stackoverflow.com/questions/18583640/program-to-figure-out-number-between-1-and-100-wont-ever-guess-100-because-of