递归的数字的平方根

时间:2015-01-25 11:42:00

标签: c++ newtons-method

#include<iostream>
#include<cmath>
using namespace std;
int e=0.001;
double yk(int k,double x){
    if(k==0) return 1;
    return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}

double square(double x,int k)
{
    if(fabs(yk(k,x)*yk(k,x) - x)<e) return yk;
    return square(x,k+1);    
}
int main()
{    
    cout<<yk(5,2);
    return 0;
}

我需要用牛顿公式计算数字的平方根,计算y [k]直到fabs(y [k] * y [k] -x)> e(一个小数字,如0.0001) );

因此,如果sqrt(2)= 1.41421356237且e = 0.0001,我的函数必须返回1.4142。

..这是我写的程序..我知道这是错误的,所以如果某人帮助我,我会非常感激:)))

1 个答案:

答案 0 :(得分:1)

变量e应为float或double。
你得到的错误不是因为fabs函数,而是因为你试图返回一个指向yk函数的指针,但是square返回一个double

#include <iostream>
#include <cmath>

using namespace std;
double e=0.001;
double yk(int k,double x){
    if(k==0) return 1;
    return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}

double square(double x,int k)
{
    double res = yk(k, x);
    if (fabs(res*res - x) < e) return res;
    return square(x,k+1);
}

int main()
{
    cout << yk(5,2); // Actually you don't call square....
    // it works even if you do square(2, 5), this way you get the root of two
    // doing at least 5 iterations, and if it is not enough (error > e) the
    // computer goes on until it gets an error < e
    return 0;
}