首页 > 解决方案 > 简单的平方根

问题描述

我在 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++rootsqrt

解决方案


#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;
}

上面的代码给出了正确的输出。我只是提高了精度。您正在使用蛮力方法找到根。您如何使用一些复杂的方法,例如Newton's Method


推荐阅读