func(int n)
// the function should return the sum of the first n term of the
// harmonic series (1/1 + 1/2 + 1/3 + ... + 1/n )
double sumover(int n)
{
if (n == 0)
return 0;
else
{
return (1. / n) + sumover(--n); // here is the bug
}
}
当使用n = 1调用该函数时,我希望它计算1。/ 1 + sumover(0)= 1/1 + 0
但是,它正在计算1./0 + sumover(0),为什么呢?
return (1. / n) + sumover(--n);
不保证该术语(1. / n)
将在之前计算sumover(--n)
。
该标准未指定。
因此,第二项可以首先计算,然后(1. / n)
变为(1. /(n - 1))
,然后得到意外的输出。
替换为
return (1. / n) + sumover(n - 1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句