0
我寫了一個簡單的c程序,用newton-raphson迭代技術找到2,3,4,5的平方根。此代碼運行僅查找並顯示2的平方根。之後它掛起。我不能與此代碼找出問題:如果你有double
替換float
到處C代碼沒有按預期運行
# 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;
}
'square'是與外部連接一起使用時的保留標識符 – ouah
您的epsilon太小,浮點類型沒有足夠的有效數字。用* double *替換所有float,以便快速修復。 –
查看[output here](http://stacked-crooked.com/view?id=a9548fc448972258896a9e17cb43e8a5),在循環中打印'guess'的值,可以很容易地看到問題。 –