【问题标题】:Why does the increment/decrement operators break the recursion functionality [duplicate]为什么递增/递减运算符会破坏递归功能[重复]
【发布时间】: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++


【解决方案1】:
return (1. / n) + sumover(--n);

不保证术语(1. / n) 将在sumover(--n) 之前计算。

标准没有规定。

因此可能会先计算第二项,然后(1. / n) 变为(1. /(n - 1)),然后您会得到意外的输出。

替换为

return (1. / n) + sumover(n - 1);

【讨论】:

  • 谢谢。您的回复很有帮助!
  • 我做到了。这是我第一次在 stackoverFlow 中提问,感谢您让我知道我可以做到这一点。
  • @AdnanMohamed UR 欢迎
猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2013-06-18
  • 2011-04-09
相关资源
最近更新 更多