Sea*_*ean 6 c algorithm recursion add sequence
嘿我试图用一点递归刷新我的想法.我想添加从"开始"到"结束"的所有数字.
即如果开始是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);
}
}
Run Code Online (Sandbox Code Playgroud)
它不起作用(我得到段故障).我究竟做错了什么?
编辑:对不起,我在我的实际代码中使用相同的变量,当我写这个,我最终作为开始/结束,并忘记更改所有代码.
你的函数里面有什么from和to变量?也许你使用一些全局变量,而不是使用的start和end,这就是为什么你有问题吗?另外你为什么sum1在calc函数内使用而不是calc?
试试这个:
int calc(int start, int end){
if(start > end)
return 0;
else
return start + calc(start + 1, end);
}
Run Code Online (Sandbox Code Playgroud)