我刚刚开始接触 C++。我编写了一个小程序,选择 1-100 之间的随机数,然后对其进行修改以使程序计算出该数字(并计算所需的猜测次数)。
程序中的所有内容都有效,除了一件事。我正在使用一个公式来猜测当前猜测值与之前的最高/最低值之间的差异,因此对于猜测来说太低了:
low = guess;
guess = (( guess + high ) / 2);
它适用于除 100 之外的所有数字。当它达到 99 时,它会将 199/2 舍入到 99,因此我会无限循环地猜测“99”。有没有办法防止这种情况或有一些公式可以解决这个问题?我知道我可以使 int high = 101 或编写一个特殊情况,如果程序将再次猜测 99,但这似乎不是对此的“干净”答案。
Thanks!
完整的程序代码:
#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 ;
And then
guess= ( low + high ) / 2 ; // = 100
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)