簡體   English   中英

計算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 = 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM