簡體   English   中英

計算平方根,但循環條件失敗

[英]calculate square root but while loop condition fails

我正在嘗試學習C ++,但是我想解決一個問題。 基本上我需要計算一個數字的平方根。 我認為我走在正確的軌道上,但是當我運行代碼時,輸​​入數字后沒有任何反應。 在此處輸入圖片說明

int n;
    double r, intGuess, guess, ratio;

    // user input
    cout << "Enter number: ";
    cin >> n;

    intGuess = n;
    guess = n / 2;
    ratio = intGuess / guess;

    while (ratio >= 1.01 || ratio <= 0.99)
    {
        r = n / guess;
        guess = (guess + r) / 2;
    }

    cout << endl;
    cout << "The square root of " << n << " is " << guess << endl;

您的循環似乎是無限的,因為您永遠不會更新其中的ratio ...那么,如果條件一次為true ,則永遠為true ...

應該是這樣的:

ratio = intGuess / guess;

while (ratio >= 1.01 || ratio <= 0.99)
{
    intGuess = guess;           // Save the previous value of guess
    r = n / guess;
    guess = (guess + r) / 2;
    ratio = intGuess / guess;   // Update ratio here with the previous and the
                                // actual value of guess
}

也:

直到猜測在先前猜測的1%以內

您應該保存先前的guess並使用此guess作為ratio ,而不是原始的guess

該算法的實時示例 我在循環中添加了兩行。

您應該將先前的猜測與當前的猜測進行比較。 那不是你在做什么。

示例:假設您輸入4。第一個猜測將是2,這是確切值。 每個連續的猜測也將為2。即使您在循環內將比率更新為IntGuess / guess,也將始終為2。

修復您的代碼,以便您將先前的猜測與當前的猜測進行比較,所有這些都很好。

暫無
暫無

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

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