c - 得到错误的平方根估计
问题描述
我用 C 语言编写了一个程序,它用苍鹭程序为我计算平方根。x
是我的号码,r
是估计值,steps
是步骤。我想输出精确值和苍鹭方法得到的值之间的差异。但似乎我的功能不正确。对于我的计算值,我没有得到任何价值。谁能帮我?
#include <stdio.h>
#include <math.h>
int heron (x, r, steps)
{
int k = 0;
double xold, xnew;
double rel_error = 1.0;
while(k <= steps && rel_error > 1e-4) {
++k;
xnew = .5 * (xold + x / xold);
rel_error = (xnew - xold) / xnew;
if(rel_error < 0)
rel_error = -rel_error;
xold = xnew;
}
printf("exact value: %.10f\n", sqrt(x));
return (xnew);
}
int main()
{
int x=4, r=10, steps=50;
printf("%f\n", heron(x, r, steps));
return 0;
}
解决方案
更改int heron (x, r, steps)
为double heron(double x, double r, int steps)
。您需要声明参数的类型,并且该函数使用浮点值,因此它应该返回float
or double
, not int
,x
andr
应该是double
。
更改double xold , xnew;
为double xold = r, xnew;
。xold
必须在使用前进行初始化。
更改return sqrt(x);
为return xold;
返回函数计算的值。
推荐阅读
- docker - 尝试安装 Metron Docker 0.7.1 版本失败
- swift - 使用匹配的正则表达式代码替换单词
- javascript - 在 node.js 中异步读取多个文件
- scala - 使用scala spark从hdfs读取写入kafka,但得到NullPointerException
- html - 内容起伏太大以至于超出边际
- c++ - 当我尝试打印出我的数组时,我得到“0x7ffeedcf3a60”作为我的输出
- git - Pip 无法再从 https 克隆 - 错误 128
- python-3.x - 如何将类实例中的所有属性和函数复制到python中的另一个类?
- regex - 无法用两个字符之间的空白替换所有内容
- java - cpu 究竟是如何运行每个线程的?