Finding the total sum of numbers in an array in Java, recursively

倖福魔咒の 提交于 2020-01-06 16:24:12

问题


I understand that finding the sum of numbers in an array is much more easily done through iteration instead of recursion, but if I were to use recursion to write such a function, what would be wrong with this code?

public static double sum (double[] a) {
    if (a.length == 0)
        return 0.0;
    else{
        return sumHelper (a, 1, a[0]);
    }
}
private static double sumHelper (double[] a, int i, double result) {
    if (i < a.length) {
        result = result + sumHelper (a, i + 1, result);
    }
    return result;
}

Everything runs without errors, yet does not return the correct sum when I test it out.


回答1:


public class RecursiveSum {
    public static void main(String[] args) {
        System.out.println(sum(new double[] {1,3,4,5}));
    }

    public static double sum(double[] a) {
        if (a.length == 0)
            return 0.0;
        else{
            return sumHelper(a, 0);
        }
    }

    private static double sumHelper(double[] a, int i) {
        if(a.length - 1 == i){
            return a[i];
        }else{
            return  a[i] + sumHelper(a, i + 1);
        }
    }
}



回答2:


Initialise the value of i to 0 because you are passing 1. or try this one

public static void main(String args[]){
    double a[]=new double[10];
    a[0]=123;
    a[1]=123;
    a[2]=123;
    a[3]=123;
    a[4]=123;
    a[5]=123;
    a[6]=123;
    a[7]=123;
    a[8]=123;
    a[9]=123;
    System.out.println(sum(a));
}



回答3:


You have problem with main method declaration:

public static void main(String args[]){
        double a[]=new double[10];
        a[0]=123;
        a[1]=123;
        a[2]=123;
        a[3]=123;
        a[4]=123;
        a[5]=123;
        a[6]=123;
        a[7]=123;
        a[8]=123;
        a[9]=123;
        System.out.println(sum(a));
    }



回答4:


If you just use a single method to recursively sum all the numbers in an array, then this is how you would go. public static void main(String[] args) {

      double a[]=new double[6]; //initialize it
        a[0]=1; //fill it with values
        a[1]=2;
        a[2]=3;
        a[3]=4;
        a[4]=5;
        a[5]=6;

        System.out.println(sum(a, a.length-1)); //call the method and print as well

}

public static double sum( double arr[], int n ) { 
      if (n < 0) {
        return 0;
      } else{
        return arr[n] + sum(arr, n-1); //magic 
      }
    }


来源:https://stackoverflow.com/questions/41712182/finding-the-total-sum-of-numbers-in-an-array-in-java-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!