带递归的数字的平方根

square root of a number with recursion

本文关键字:平方根 数字 递归      更新时间:2023-10-16
#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 。

..这是我写的程序。我知道这是有问题的,所以如果 sb 帮助我:)))

变量 e 应该是浮点数或双精度数。
您得到的错误不是因为 fabs 函数,而是因为您尝试返回指向 yk 函数的指针,但 square 返回一个双精度

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