c/c++语言开发共享递归地添加数字序列

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

即如果开始是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); } 

      以上就是c/c++开发分享递归地添加数字序列相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/560093.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐