递归添加数字序列 [英] Recursively add sequence of numbers

查看:114
本文介绍了递归添加数字序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我试图通过递归来刷新我的想法。
我想将所有从开始到结束的数字加起来。

Hey im trying to refresh my mind with a bit of recursion. I want to add all numbers from 'start' to 'end' inclusive.

即,如果start为1,end为5,那么答案将是是1 + 2 + 3 + 4 + 5 = 15

I.e if start was 1, and end was 5. Then the answer would be 1+2+3+4+5 = 15

到目前为止,我已经拥有了

So far I've got this

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

它不起作用(出现段错误)。我在做什么错?

Its not working (i get seg fault). What am i doing wrong?

编辑:对不起,我在实际代码中使用了相同的变量,当我编写此代码时,我最终将它们作为开始/结束和忘记更改所有代码。

Sorry i am using the same variables in my actual code, when i wrote this i ended up reffering to them as start/end and forgot to change all the code.

推荐答案

什么是 from 函数中的变量?也许您使用一些全局变量而不是使用 start end ,这就是为什么您遇到问题了?另外,为什么在 calc 函数内使用 sum1 而不是 calc

What are from and to variables inside your function? Maybe you use some globals instead of using start and end and that's why you have the problem? Also why are you using sum1 inside the calc function instead of calc?

尝试以下操作:

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

这篇关于递归添加数字序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆