简易方块铲运机 [重复]

问题描述 投票:0回答:1

我在C++课之间,所以为了保持练习,我写了一个找根的程序。

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double input;
    bool done = false;
    static double check;

    while (done == false)
    {
        cout << "what number to root? ";
        cin >> input;
        bool foundRoot = false;
        check = input;
        while (foundRoot == false)
        {
            if (check * check == input || check*check < input)
            {
                foundRoot = true;
                //done = true;
            }
            else
            {
                check = check - .00001;
            }
        }
        cout << "The root of " << input << " is " << setprecision(7) << check << endl;
    }

}

这个程序似乎对任何测试过的平方都能返回正确的值(甚至是非完美的);但是输入 "25 "就会返回4.9999~。为什么会这样?

c++ root sqrt
1个回答
2
投票
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double input;
    bool done = false;
    static double check;
    cout << "what number to root? ";
    cin >> input;   
    bool foundRoot = false;
    check = input;
    while (!foundRoot)
    {
        if (check * check <= input)
        {
            foundRoot = true;
        }
        else
        {
            check = check - .000001;
        }
    }
    cout << "The root of " << input << " is " << setprecision(7) << check << endl;
}

以上代码给出了正确的输出。我只是增加了精度。你在使用蛮力方法来寻找根。不如你用一些复杂的方法,比如 牛顿法.

© www.soinside.com 2019 - 2024. All rights reserved.