预定义的squareroot函数,不使用C中的math.h中的sqrt()

时间:2009-01-25 00:39:17

标签: c windows math

家庭作业问题:

  • Cygwin GNU GDB
  • Cygwin GNU GCC

尝试从 A 幂2的平方根和 B 幂2的平方根确定斜边 C的长度。

示例输入:

输入直角三角形的两边长度:2.25 8.33

答案:

斜边的长度为:8.628523

  • 问题当我指定与上面相同的输入时,结果不是相同 - 输出 19.84.9596

下面的完整代码

float squareRoots(float *s)
{
    float cx;
    float nx;
    float e;

    cx = 1;
    nx = (cx +*s/cx)/2;
    e = nx - cx;
    cx = nx;

    if (e*e > 0.001)
    {
        nx = (cx +*s/cx)/2;
        return nx;
    } else {
        return nx;
    }
}

float hypotenuse(float *a, float *b)
{
    float c;
    //raise a to power of 2
    *a = (*a * *a);
    *b = (*b * *b);
    //add a and b
    float y = *a + *b;
    c = squareRoots(&y);

    return c;
}


int main()
{
    float x,y;

    printf("Enter the length of two sides of a right-angled triangle:");
    scanf("%f %f", &x, &y);
    float k=hypotenuse(&x,&y);

    printf("The length of the hypotenuse is: %f", k);

    exit(0);
}

3 个答案:

答案 0 :(得分:6)

您(应该是?)使用的平方根算法称为Newton's method。你的if语句应该是一个while循环。

替换

if (e*e > 0.001)
{
        nx = (cx +*s/cx)/2;
        return nx;
} else {
        return nx;
}

使用while循环迭代地执行相同操作,但包括重新计算e。

我会给你工作代码,但你说这是功课。如果您无法使用它,请发布新代码,我们将很乐意帮助您排除故障。

答案 1 :(得分:3)

想要实现超级直方根吗?查看John Carmack's magic square root from Quake III

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the ****?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

答案 2 :(得分:0)

我的答案是8.628522469,即8.628522。

相关问题