首页 > 解决方案 > 得到错误的平方根估计

问题描述

我用 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;
}

标签: calgorithmsquare-root

解决方案


更改int heron (x, r, steps)double heron(double x, double r, int steps)。您需要声明参数的类型,并且该函数使用浮点值,因此它应该返回floator double, not intxandr应该是double

更改double xold , xnew;double xold = r, xnew;xold必须在使用前进行初始化。

更改return sqrt(x);return xold;返回函数计算的值。


推荐阅读