[英]Finding the total sum of numbers in an array in Java, recursively
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. 一切正常运行,但在我测试时并没有返回正确的总和。
Initialise the value of i to 0 because you are passing 1. or try this one 将i的值初始化为0,因为您正在传递1.或尝试使用此值
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));
}
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);
}
}
}
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));
}
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) {
公共静态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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.