【问题标题】:Getting wrong square-root estimation得到错误的平方根估计
【发布时间】:2021-02-22 17:02:23
【问题描述】:

我用 C 语言编写了一个程序,它用heron procedure 为我计算平方根。 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;
}

【问题讨论】:

  • But it seems that my function is not correct你能扩展一下吗?
  • 嗯,它返回(并打印两次)sqrt(x) 的值,而不是计算出来的值。
  • 打开编译器警告并将其视为错误。这在多个方面都被打破了。未初始化的xold 和错误的返回类型(应该是double,而不是int)等等。
  • For my calculated value i get no value 这是什么意思?什么变量保存了您的计算值,它“没有值”意味着什么?
  • 您的 printf 语句需要一个浮点数 - "%f\n" - 但 heron 返回一个 int。似乎这可能是一个因素。

标签: c algorithm square-root


【解决方案1】:

带有这个前缀

int heron (x, r, steps)
{

您的函数是一个接受整数 x、另一个整数 r 和第三个整数 steps 的函数。事实上,它还返回一个整数。

你描述的算法可以这样实现:

#include <stdio.h>
#include <math.h>

double heron(double x, double err)
{
    double a = x, b = 1.0;
    while (a - b > err) {
        a = (a + b)/2.0; /* arithmetic mean */
        b = x / a; /* approx to geometric mean */
    }
    return a; /* or b, depending if you want a value in excess or in defect */
}

int main()
{
        printf("heron(2.0, 1.0E-10) = %.10f\n", heron(2.0, 1.0E-10));
        printf("sqrt(2.0) = %.10f\n", sqrt(2.0));
}

这将起作用。 阅读 C 编程语言的众多参考资料之一中的函数参数类型定义,例如Brian Kernighan 和 Dennis Ritchie 的“C 编程语言”,供参考。

$ ./heron
heron(2.0, 1.0E-10) = 1.4142135624
sqrt(2.0) = 1.4142135624
$ _

【讨论】:

  • 好的,谢谢您的帮助。我现在很清楚了。
  • @JohnBlack,您应该选择一个答案作为所选答案
【解决方案2】:

int heron (x, r, steps) 更改为double heron(double x, double r, int steps)。您需要声明参数的类型,并且该函数使用浮点值,因此它应该返回floatdouble,而不是int,并且xr应该是@987654328 @。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多