牛顿方法找到立方根,每次答案为0

时间:2017-02-09 17:47:27

标签: c++ newtons-method

我正在使用一个带有C ++的程序,它将使用牛顿方法计算给定浮点数的立方根。我的程序编译,但答案总是为零。这是该计划:

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

int main()
{
    const double epsilon = 0.00000001;
    double A = 0;
    double x1 = A / 10;
    double x2 = 0;
    int iter = 0;

    cout << "Please enter a number to square. " << endl;
    cin >> A;

    while ((fabs(x1 - x2) > epsilon) && (iter < 100)) {
        x1 = x2;
        x2 = ((2 / 3 * x1) + (A / (3 * x1 * x1)));
        ++iter;
    }

    cout << "The answer is : " << x2 << endl;
}

1 个答案:

答案 0 :(得分:3)

您将变量分配为零,因此您没有进入循环,并且您也将零除以零,因为您设置了x1=x2以及评论中所说的内容。所以我移动了一些分配和声明,一切都很顺利

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

int main()
{
    const double epsilon = 0.00000001;
    double A = 0;
    double x1 = 0;
    double x2 = 1;
    int iter = 0;

    cout << "Please enter a number to square. " << endl;
    cin >> A;
    x1 = A / 10.0;
    while ((fabs(x1 - x2) > epsilon) && (iter < 100)) {
        x1 = x2;
        x2 = ((2.0 / 3.0 * x1) + (A / (3.0 * x1 * x1)));
        ++iter;
    }

    cout << "The answer is : " << x2 << endl;
}