C代码未按预期运行

时间:2012-12-21 12:43:43

标签: c

我写了一个简单的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;
}

1 个答案:

答案 0 :(得分:1)

如果您将float替换为double无处不在,那么一切都会正常工作。