C语言 递归语句中返回的值与计算的值不同



我正在尝试使用牛顿方法计算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.2fn", 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;
}

请更改

a = (a + x / a) / 2;
newtonRec(x, a, eps);

a = (a + x / a) / 2;
return newtonRec(x, a, eps);
> $./a.out> ****189.04**** 35735.0 的平方根为:189.04

最新更新