0

我编写了一个简单的 c 程序来使用 newton-raphson 迭代技术找到 2、3、4、5 的平方根。此代码仅用于查找和显示 2 的平方根。之后它挂起。我无法弄清楚这段代码的问题:

# include<stdio.h>

    float square(float x);
    float absolutevalue(float x);

int main(void)
{
    printf("square root of 2 is %f\n", square(2));
    printf("square root of 3 is %f\n", square(3));
    printf("square root of 4 is %f\n", square(4));
    printf("square root of 5 is %f\n", square(5));

    return 0;
}

float square(float x)
{
    float epsilon = 0.0000001;
    float guess = 1;

    while (absolutevalue(guess*guess - x) >= epsilon)
        guess = ((x/guess) + guess) / 2;

    return guess;
}

float absolutevalue(float x)
{
    if (x < 0)
        x = -x;

    return x;
}
4

1 回答 1

1

如果你floatdouble任何地方替换一切都会正常工作。

于 2012-12-21T14:23:34.853 回答