我想使用包含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;
}
提示:测试精确相等的浮点值几乎总是一个错误。 –
您的循环永远不会结束,因为循环条件不满足。找出它为什么不满意,或什么时候应该满足。 – Imprfectluck
如果你想知道为什么:'printf(“%f \ n”,absoluteValue((guess * guess)/ x));' –