递归求数组元素的总和

Find the sum of array elements recursively

我有以下学校作业: public static double sum(double [] a, int low, int high)

即returns数组切片a[low:high]中所有数字的总和。

如果低 > 高,它会抛出 IllegalArgumentException。否则,它检查是否 切片有 1 个项目。如果是这样,它 returns 该值。

如果切片有 2 个或更多项,它将切片分成 2 个相等的子切片,计算总和 2 个子切片的和 returns 2 个部分和的总和。 这是我写的: 我对递归真的很不好,这就像我写的第一个递归代码。

public static  double sum(double [] a, int low, int high) throws Exception{
    if(low > high){
        throw new IllegalArgumentException();
    }
    else if(low == high){
        return a[low];  
    }   
    return sum(a, low, high/2) + sum(a, high/2, high);
}

我离答案还有多远? 更新: 这是我正在执行的所有代码:

public class ArraySum {
    int low; 
    int high;
    double []list;


    public ArraySum(int lowIn, int highIn, double []listIn){
        low = lowIn;
        high = highIn;
        list = listIn;  
    }
    public double auxSum() throws Exception{
        return sum(list, low, high);
    }
    public static  double sum(double [] a, int low, int high) throws Exception{
        if(low > high){
            throw new IllegalArgumentException();
        }
        else if(low == high){
            return a[low];  
        }   
        return sum(a, low, (high+low)/2) + sum(a, (high+(low+1))/2, high);
    }
}

这是我的主要内容:

public class Main {

    public static void main(String[] args) throws Exception {
        double [] l = {1,2,3,4,5};
        ArraySum a = new ArraySum(0, 5, l);
        System.out.println("the sum is: " + a.auxSum());

    }
}

你快明白了!这里有一些提示:

  • high/2 不太对。 (想想如果 low = 98 和 high = 100 会发生什么。)

  • 当你递归你需要记住你传递的索引是包含,所以在第二次递归调用我建议你加1到较低的索引(这样它就不会与第一个递归调用的较高索引重叠)

如果你想让我澄清任何一项,请告诉我。