在下面的代码中,我想将终止条件替换为:如果猜测平方和 x 的比率接近 1,则 while 循环应该终止。我尝试了各种表达式,但没有一个能正确运行代码。有什么建议吗?
# include<stdio.h>
float absolute(float x)
{
if (x < 0)
x = -x;
return x;
}
float square(float x)
{
float guess = 1;
while(absolute(guess*guess - x) >= 0.0001 )
guess = ((x/guess) + guess) / 2;
return guess;
}
int main(void)
{
printf("square root of 2 is %f\n", square(2));
printf("square root of 3 is %f\n", square(3));
return 0;
}