2016-04-01 107 views
1

我想使用包含while循环的函数来计算数字的平方根。在while循环的条件下,我想比较两个值(猜测的平方根和数字)的比值的绝对值为1.但是,无论何时运行程序,我都会得到一个无限循环输出1.414214。任何帮助?谢谢。使用while循环来计算数字的平方根的近似值

// 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; 
} 
+2

提示:测试精确相等的浮点值几乎总是一个错误。 –

+1

您的循环永远不会结束,因为循环条件不满足。找出它为什么不满意,或什么时候应该满足。 – Imprfectluck

+1

如果你想知道为什么:'printf(“%f \ n”,absoluteValue((guess * guess)/ x));' –

回答

4

更改此:

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

要:

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

你要继续优化你的答案,直到它内的目标epsilon。您需要从比例中减去1.0,以获得您所看到的与您的目标之间的差异,然后在差异在epsilon之内时停止。你不想继续尝试,如果它是更小epsilon

对于epsilon,您还需要使用更小的值,例如, 0.000001

+0

或者'fabs(guess * guess-x)> epsilon'是否需要绝对容错(例如+/- 0.01而不是+/- 1%)。 – MooseBoys

+0

@MooseBoys是的,这可能是一个更好的方法来做到这一点。我只是试图使现有的测试达到预期目的。 –