使用while循环计算数字的平方根的近似值

时间:2016-04-01 00:47:37

标签: c function while-loop square-root

我正在尝试使用包含while循环的函数来计算数字的平方根。在while循环的条件下,我想比较两个值(猜测的平方根和数字)的比率的绝对值为1.但是,每当我运行程序时,我都会得到无限循环输出 1.414214 即可。有帮助吗?感谢。

// Function to calculate the absolute value of a number

#include <stdio.h>

float absoluteValue (float x)
{
    if ( x < 0 )
        x = -x;
    return (x);
}

// Function to compute the square root of a number

float   squareRoot (float x, const float epsilon)
{
    float       guess = 1.0;

    while ( absoluteValue ((guess * guess) / x) != epsilon ) {
        guess = ( (x / guess) + guess ) / 2.0;
        printf("%f\n", guess);
    }

        return guess;
}

int main (void)
{
    printf ("squareRoot (2.0) = %f\n", squareRoot (2.0, 1.0));
    printf ("squareRoot (144.0) = %f\n", squareRoot (144.0, 1.0));
    printf ("squareRoot (17.5) = %f\n", squareRoot (17.5, 1.0));

    return 0;
}

1 个答案:

答案 0 :(得分:4)

改变这个:

while ( absoluteValue ((guess * guess) / x) != epsilon ) {

要:

while ( absoluteValue ((guess * guess) / x - 1.0) > epsilon ) {

您希望继续优化您的答案,直到它在目标的epsilon范围内。您需要从比率中减去1.0,以获得您所看到的内容与目标之间的差异,然后您希望在差异在epsilon之后停止。如果 ,则不想继续尝试。

您还需要为epsilon使用更小的值,例如epsilon