c++ - 牛顿法求立方根,结果每次都是0

标签 c++ newtons-method

我正在使用一个 C++ 程序,它将使用牛顿法计算给定 float 的立方根。我的程序可以编译,但结果总是为零。这是程序:

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

最佳答案

您将变量分配为零,因此您不会进入循环并且您还被零除,因为您设置了 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;
}

关于c++ - 牛顿法求立方根,结果每次都是0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42143508/

相关文章:

java - Java中如何理解牛顿求平方根法?

matlab - Matlab 中的 Newton-Raphson 方法

c++ - 为什么我们可以访问 switch 的其他 case 标签内的变量?

c++ - unique_ptr : linked list entry deletion

matlab - 用MATLAB写一个二维实现牛顿法的函数

c++ - C++中的牛顿正切方法

r - 求解简单的(?)非线性方程组

c++ - 日期函数定义的伪代码

访问成员 unordered_map 中的数据时,C++ const 方法在结构中编译错误

c++ - 使用 cin.ignore() 跳过 2 个空格