简体   繁体   English

C - n个自然数之和的递归函数

[英]C - recursive function for sum of n natural numbers

Below is the recursive function for sum of natural numbers up to n . 下面是自然数之和为n的递归函数。

int calculateSum(int n) {
    if (n == 0){
        return 0;
    }else{
        return n + calculateSum(--n); //Replacing --n with n-1 works
    }
}

Input: 5 输入:5

If I use --n then the output is 10 , but when I replace --n with n - 1 then the correct result is returned (15). 如果我使用--n那么输出是10 ,但是当我n - 1替换--n返回正确的结果(15)。 Why the difference? 为什么不同?

As surprising as it might be, the behaviour of the expression 令人惊讶的是,表达式的行为

n + calculateSum(--n);

is undefined , because --n not only evaluates to the value of n after being decremented by 1, it also changes n to the new value. 未定义 ,因为--n不仅在递减1后计算n的值,它还将n更改为新值。 The change (a side effect), however, is unsequenced in relation to the other evaluation of n (a value computation) on the left. 然而,相对于左侧的n (值计算)的其他评价,该变化(副作用)是未确定的。 And according to C11 Appendix J.2. 并根据C11附录J.2。 , the behaviour is undefined, when ,行为未定义,何时

A side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object (6.5) . 相对于对同一标量对象的不同副作用或使用相同标量对象的值计算值(6.5) ,对标量对象的副作用是无序的。

More of the same class of errors in this question . 这个问题中有更多同类错误。


You can consider yourself lucky when you got a wrong value, because your compiler could have also generated code that would return the "correct value" ... given the phase of the moon, and the optimization settings, or the number of lines in the calling function... 当你得到一个错误的值时,你可以认为自己很幸运,因为你的编译器也可以生成代码,它会返回“正确的值” ...给定月相,优化设置或者行中的行数。呼叫功能......

--n also modifies the local variable n ; --n还修改局部变量n ; the expression n-1 just returns the decremented value to pass it on to the recursive call, but does not modify your input-parameter. 表达式n-1只返回递减的值以将其传递给递归调用,但不会修改输入参数。

In detail for the first iteration with input 5 : 详细介绍输入5的第一次迭代:

  • Correct is return 5 + calculateSum(5-1); 正确的是return 5 + calculateSum(5-1);
  • With --n you would also decrement from n and end up with 4 + calculateSum(4) 使用--n你也会从n递减并最终得到4 + calculateSum(4)

@user3386109 & @Yunnosch worded it this way: With --n you calculate the sum 0...(5-1) instead of 0...5 . @ user3386109&@Yunnosch用这种方式措辞:用--n计算总和0...(5-1)而不是0...5

See @Antti answer, it explains that it's actually undefined behaviour. 请参阅@Antti的答案,它解释了它实际上是未定义的行为。

The following code snippet (a Function), you can call it in the main function which will return the sum of n natural numbers recursively 下面的代码片段(一个Function),你可以在main函数中调用它,它将递归地返回n个自然数的总和

int NNumbers(int n)
{
    if(n != 0)
        return n + NNumbers(n-1);
    else
        return n;
}

In your code you are decrementing the value of n and then you are calculating the sum (i,e. Pre-Decreament), since the input is 5, it decrements 1 at each iteration and and then it will go for addition of natural numbers. 在你的代码中,你递减n的值,然后你计算总和(i,例如Pre-Decreament),因为输入是5,它在每次迭代时递减1然后它将添加自然数。 so you are getting the result 10 instead of 15 所以你得到的结果是10而不是15

hope this helps for you :) thank you 希望这对你有所帮助:)谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM