2011-05-09 81 views
6

嘿即时尝试刷新我的思想与一些递归。 我想添加从'开始'到'结束'的所有数字。递归添加数字序列

也就是说,如果开始为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故障)。我究竟做错了什么?

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

+0

切勿使用增量运营商时, 'start + 1'也可以。 – hugomg 2011-05-09 13:45:16

回答

7

什么是fromto变量里面的函数?也许你使用一些全局变量而不是使用startend,这就是为什么你有这个问题?另外你为什么在calc函数内使用sum1而不是calc

试试这个:

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

谢谢:) 你首先回答说有(开始++,结束)在它导致了一个分段错误,但开始+1工作。为什么是这样? – Sean 2011-05-09 04:34:19

+4

它应该是++的开始。预先增量而不是后增量。 start ++永远不会递增传递给递归函数的值并导致无限循环。因此分段错误。 – 2011-05-09 04:40:16

+0

真棒回复Spendor,谢谢:D – Sean 2011-05-09 04:44:24

3

首先,你不使用你的函数参数(开始,结束),你正在使用(从,到)来代替。我假定来自或者是全局变量,或者你的代码不能编译。此外,总申报在哪里?

这应该更好地工作:

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

我觉得你的递归调用需要'++ start'。 – 2011-05-09 04:15:00

+1

实际上应该是'start + 1'。 'start ++'是错误的,因为它可以在语句前面的'start +'之前进行评估。 – ikegami 2011-05-09 04:36:54

+0

哦,你们是对的,我认为看起来有趣,我应该改变它。 – GWW 2011-05-09 04:56:25

0

这工作得很好。

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

'from ++'是错误的,因为它可以在语句前面的'from'之前进行评估。它应该是从+ 1开始的。 – ikegami 2011-05-09 04:37:19

+1

它不是从++而是从++。 (预增) – 2011-05-09 04:38:54

+1

同样适用于'++ from'。 '++ from'是错误的,因为它可以在语句前面的'from'之前或之后进行评估。通常,不应该同时在表达式中更改和使用变量。 – ikegami 2011-05-09 04:47:18

3

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

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

+0

我认为这个问题的最佳解决方案是由ikegami提出的。 有时你不必像现在这样解决问题,并想出不同的方法来计算相同的事情。 ikegami所展示的是一个简单的算法,用于将一系列的和加到一定数量上。它的工作效率也很高。 – Abhay 2011-05-09 14:54:15