由于四舍五入,计算 1 到 100 之间的数字的程序永远不会猜"100"
Program to figure out number between 1 and 100 won't ever guess "100" because of rounding
我刚刚开始使用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;
}
相关文章:
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 用于检查数字是否有数字或可被该数字的值整除的程序
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 为什么当我输入较大的数字时,我的程序会到达文件末尾?
- 如何在C++程序中使用下标数字?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何在 WindowProc 处理程序中区分箭头键和数字键盘?
- 在 txt 文件中显示前两个数字的程序
- 在不添加进位的情况下添加数字的C++程序
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 每次运行此 c++ 程序时如何获得不同的数字?
- 程序 查找数字的重复
- 反转一个数字程序不起作用,为什么?
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 如何制作一个查找数字平方值的 c++ 程序
- 双精度数字程序意外值
- For循环-魔术数字程序
- 完全数字程序中的逻辑错误