我正在使用一个 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/