4

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;

}
4

3 回答 3

2

另一种选择是你从

    int high= 101 ;

你永远不会要求101,因为在最坏的情况下你会得到

    low= 99 ;
    high= 101 ;

接着

    guess= ( low + high ) / 2 ;   // = 100
于 2013-09-03T03:42:30.627 回答
1

尝试

low = guess;    
guess = (( guess + high +1) / 2);
于 2013-09-03T03:34:36.153 回答
1

好吧,您的代码的问题很明显:

else if(guess<number)
{
low=guess;
}

这里的问题是您为猜测的数字分配了下限,但这不合逻辑,因为猜测低于数字,因此改为使用:

low=guess+1;

这段代码不仅解决了这个问题,而且降低了执行时间,因为类似地检查的数量会更少:

else
{
high=guess-1;
}
于 2013-09-03T12:54:35.540 回答