我正在尝试使用牛顿法计算x的平方根。一切正常,a等于x的平方根,直到它返回给我一个完全不同的(总是恒定的)更大的数字时才返回它。
int main()
{
float newtonA;
float newtonX = 35735;
float epsilon = 0.001;
newtonA = newtonX / 2;
printf("\n********RECURSIVE NEWTON********\n");
printf("The square root of %0.1f is: %0.2f\n", newtonX, newtonRec(newtonX, newtonA, epsilon));
return 0;
}
float newtonRec (float x, float a, float eps)
{
if (abs(a * a - x) <= eps )
{
printf("\n****%0.2f****\n", a);*/
return a;
}
else
{
printf("\n***a: %.1f x: %.1f***\n", a, x);
a = (a + x / a) / 2;
newtonRec(x, a, eps);
}
return a;
}
答案 0 :(得分:0)
请更改
a = (a + x / a) / 2;
newtonRec(x, a, eps);
到
a = (a + x / a) / 2;
return newtonRec(x, a, eps);
> $./a.out > ****189.04**** The square root of 35735.0 is: 189.04