简体   繁体   中英

calculate square root but while loop condition fails

I'm trying to learn C++ and there is a problem I am trying to work out. Basically I need to calculate the square root of a number. I think I'm on the right track, but when I run the code nothing happens after I input a number. 在此处输入图片说明

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;

Your loop seems to be infinite because you never update ratio inside it... then if the condition is true once, it is true forever...

It should be something like:

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
}

Also:

until guess is within 1% of the previous guess

You should save the previous guess and use this one for your ratio , not the original one.

Live example of this algorithm. I added two lines in the loop.

You are supposed to be comparing the previous guess to the current one. That's not what you are doing.

Example: Suppose you input 4. The first guess is going to be 2, which is the exact value. Every successive guess will also be 2. Even if you update the ratio as IntGuess/guess inside the loop, it's going to be 2. Always.

Fix your code so you are comparing the previous guess and the current one and all will be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM