我的C代码中有一个连续的循环,我不明白它为什么会这样。我觉得我错过了一些值得注意的东西,但我只是因为某些原因看不见。下面是导致循环的代码段:
while (err > 0.0000001) {
if (err != 1.0) {
bab = ((2.0*bab) + input/(pow(bab, 2)))/3.0;
printf("The approximate cube root is %.3lf\n", bab);
err = input - bab;
}
else {
bab = ((2.0*app) + input/(pow(app, 2)))/3.0;
printf("The approximate cube root is %.3lf\n", bab);
err = input - bab;
}
}
如有任何帮助,我们将不胜感激。
最佳答案
bab
(或早或晚)近似为input
的立方根。你设置
err = input - bab;
测试
while (err > 0.0000001)
因此,如果
input > 1 + 3*1e-7
(大致上),差异input - cube_root(input)
大于阈值。你可能想设定
err = abs(input - bab*bab*bab);
来控制对
input
的立方根近似的质量。