Home  >  Q&A  >  body text

c++ - 这个使用牛顿迭代法求立方根的程序哪里错了?

运行结果不正确,不知道为什么,希望能够得到指教。

#include <iostream>
#include <math.h>
using namespace std;
int main(){
double a,x,y;
cin>>a;
do{
    x = a;
    y = (2/3)*x+a/(3*x*x);
    x=y;
}
while(fabs(a-x) < 0.00001);
cout<<x<<endl;

}


PHPzPHPz2714 days ago750

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 14:55:06

    Update: Please also pay attention to the boundary conditions. If my value is 0, it needs to be processed separately

    #include <iostream>
    #include <math.h>
    using namespace std;
    int main(){
        double a,x,y;
        cin>>a;
        x = a;        // 不应该放在循环体内
        do{
            y=(2/3.0)*x+a/(3*x*x); //精度问题 2/3会自动转为0
            x=y;
        }while(fabs(a-x*x*x)>0.0001); // 应该用立方去比较, 大于小于号写反
        cout<<x<<endl;
    
    }

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:55:06

         x = a;
         y = (2/3)*x+a/(3*x*x);
         x=y;

    Problem:
    1>. If the program iterates, the value of a will not change, which will cause the value of x to always be the input value. It should be written as
    x = ((2.0) / 3)*x + a / (3 * x*x); //将 x=a 放在do语句之前
    2>. The value of (2/3) is 0. If you want to calculate floating point numbers, it should be written as (2.0/3)
    The above two are program errors.

    while(fabs(a-x) < 0.00001);

    Problem:
    3>. The bool value returned after the first iteration of the judgment condition of the while statement is 0, and the loop is jumped out at this time.

    If there is anything wrong with your answer, thank you for pointing it out

    reply
    0
  • Cancelreply