递归地添加数字序列

嘿我试图用一点递归刷新我的想法。 我想添加从“开始”到“结束”的所有数字。

即如果开始是1,结束是5.那么答案将是1 + 2 + 3 + 4 + 5 = 15

到目前为止,我已经有了这个

int calc(int start, int end){ if(start > end) return total; else{ total = total + start; return sum1(start++, end); } } 

它不起作用(我得到seg故障)。 我究竟做错了什么?

编辑:对不起,我在我的实际代码中使用相同的变量,当我写这个我最终作为开始/结束,他们忘记改变所有代码。

你的函数里面和变量是什么? 也许你使用一些全局变量而不是使用startend ,这就是你遇到问题的原因? 另外你为什么在calc函数中使用sum1而不是calc

试试这个:

 int calc(int start, int end){ if(start > end) return 0; else return start + calc(start + 1, end); } 

对于初学者,您没有使用函数参数(开始,结束),而是使用(从,到)。 我假设from和to是全局变量,或者你的代码不能编译。 此外,在哪里宣布总数?

这应该更好:

 int calc(int start, int end){ if(start > end) return 0; else{ return start + calc(start+1, end); } } 

顺便说一句,这是一个更有效的解决方案:

 int calc(int from, int to) { if (from == 0) return to * (to+1) / 2; else return calc(0, to) - calc(0, from); } 

它甚至是递归的! 好吧,直到你进一步简化它为止

 int calc(int from, int to) { return ( to * (to+1) - from * (from+1) ) / 2; } 

那是因为f(n)= n + … + 3 + 2 + 1 = n(n + 1)/ 2

这适用于。

 int calc(int from, int to) { if (from >= to) return to; return from + calc(from + 1, to); }