由于四舍五入,计算 1 到 100 之间的数字的程序永远不会猜"100"

Program to figure out number between 1 and 100 won't ever guess "100" because of rounding

本文关键字:数字 程序 永远 之间 四舍五入 计算      更新时间:2023-10-16

我刚刚开始使用C++。我写了一个小程序,可以选择1-100之间的随机数,然后对其进行修改,使程序计算出数字(并计算所需的猜测次数)。

程序中的所有内容都有效,只有一件事除外。我使用了一个公式来猜测当前猜测和之前最高/最低值之间的差异,所以对于过低的猜测:

low = guess;
guess = (( guess + high ) / 2);

它适用于除100以外的所有数字。当它达到99时,它会从199/2到99,所以我得到了一个无休止的"99"猜测循环。有没有办法防止这种情况发生,或者有什么公式可以解决这种情况?我知道,如果程序第二次要猜99,我可以让int high=101,或者写一个特例,但这似乎不是一个"干净"的答案。

谢谢!

完整的程序代码:

#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;
}

另一种选择是从开始

    int high= 101 ;

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

    low= 99 ;
    high= 101 ;

然后

    guess= ( low + high ) / 2 ;   // = 100

尝试

low = guess;    
guess = (( guess + high +1) / 2);

代码的问题很明显:

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

这里的问题是,你给猜测的数字指定了下限,但这是不符合逻辑,因为猜测比数字低,所以改为使用:

low=guess+1;

此代码不仅解决了问题,而且降低了执行时间,因为要检查的数字较少类似:

else
{
high=guess-1;
}