带递归的数字的平方根
square root of a number with recursion
#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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 试图找到一个数字的平方根,但代码不起作用。C++
- 使用位移算法计算平方根始终输出相同的数字
- 如何获取数组中每个数字的平方根 (C++)
- 如何用3个用户定义的函数计算一个数字的真平方根
- 带递归的数字的平方根
- 如何输入正数并打印出平方根,直到输入的数字
- 计算数字平方根的程序
- 平方根为2,点后需要x位数字
- 在C++中,平方根返回的不是数字
- 我的平方根函数对某些数字不能给出准确的结果