问题
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