【发布时间】:2020-04-03 04:05:38
【问题描述】:
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) ,为什么?
【问题讨论】:
-
这也是未定义的行为(
--n中的赋值相对于1. / n中的读取是无序的)
标签: c++