JAVA:使用递归从头到尾添加

JAVA:使用递归从头到尾添加,java,recursion,Java,Recursion,我需要这个递归方法的帮助。我需要它把从起点到终点的整数相加 public static int sumInts(int begin, int end){ if (begin == end) return begin + end; else return sumInts(begin+1,end); } 示例输出应为: 起点:1 完:4 总数为:10 但是对于这些特定的输入,我得到了8作为我的输出。我知道是这种情况毁了这一切,但我似乎无法理

我需要这个递归方法的帮助。我需要它把从起点到终点的整数相加

    public static int sumInts(int begin, int end){
    if (begin == end)
        return begin + end;
    else
        return sumInts(begin+1,end);
}
示例输出应为: 起点:1 完:4 总数为:10

但是对于这些特定的输入,我得到了8作为我的输出。我知道是这种情况毁了这一切,但我似乎无法理解

但是对于这些特定的输入,我得到了8作为我的输出

这很正常。它每次都会转到else块,但最后一次是,因为begin和end都是4,它将返回4+4=8

你应该这样做:

public static int sumInts(int begin, int end){
    if (begin == end)
        return end; // return the last number
    else
        return begin + sumInts(begin+1,end); // sum the current number with the recursion result
}
当然,这可以通过另一种方式实现——减少结束而不是增加开始

但是对于这些特定的输入,我得到了8作为我的输出

这很正常。它每次都会转到else块,但最后一次是,因为begin和end都是4,它将返回4+4=8

你应该这样做:

public static int sumInts(int begin, int end){
    if (begin == end)
        return end; // return the last number
    else
        return begin + sumInts(begin+1,end); // sum the current number with the recursion result
}
当然,这可以通过另一种方式实现——减少结束而不是增加开始


在sumInts1,1的情况下,您期望得到什么?如果您仔细查看您的代码,它本质上是returnend+end;在第5行中,将代码更改为-return begin+sumIntsbegin+1,end@PM77-1我应该看到的。开始1和结束1应该是1。@SanjitKumarMishra是的,这与下面的解决方案是一致的。在sumInts1,1的情况下,你会期望什么?如果你仔细看你的代码,它本质上是返回end+end;在第5行中,将代码更改为-return begin+sumIntsbegin+1,end@PM77-1我应该看到的。“开始1和结束1应该是1”。@SanjitKumarMishra是的,这与下面的解决方案是一致的。