使用Java递归在数组中找到正元素的总和
问题描述 投票:0回答:2
嗨,我只是在学习递归,我试图用Java编写一个递归程序来查找数组中所有正元素的和。使用:这是预期的输出:0 5 7 3 0 17import java.util.Arrays;
public static void main(String[] args) {
int[] list0 = new int[] {};
int[] list1 = new int[] { 5 };
int[] list2 = new int[] { 3, 4 };
int[] list3 = new int[] { -2, 3, -4 };
int[] list4 = new int[] { -1, -2, -4, -5 };
int[] list5 = new int[] { 6, 1, 2, -3, 8 };
}
public static int sumOfPositivesRecursive (int[] a) {
return sumOfPositivesHelper(a, a.length);
}
public static int sumOfPositivesHelper(int[] a, int n) {
if(n == 0) {
return 0;
}
System.out.println(n);
int total = 0;
if(a[n-1] > 0) {
total += a[n-1];
sumOfPositivesHelper(a, n-1);
}
return total;
}
我的输出:0 5 4 0 0 8,似乎只在第一次检查最后一个元素,而不再循环。请帮助我知道我在递归调用中做错了什么。谢谢大家。
java
arrays
recursion
2个回答
1
投票
public static int sumOfPositivesRecursive (int[] a) {
Int i =0
return sumOfPositivesHelper(a, i, 0);
}
public static int sumOfPositivesHelper(int[] a, int i, int sum) {
if(i == a. length) {
return sum;
}
if(a[i] > 0) {
sum+= a[i];
sumOfPositivesHelper(a, i++, sum);
}
}```
Try this sorry it should work but im not sure because at the momento I cant Try it
1
投票
您的代码未正确使用递归,因为总变量未在sumOfPositivesHelper调用之间传递且未正确处理,有效的解决方案将是这样的:package test;
public class Main {
public static void main(String[] args) {
System.out.println(sumOfPositives(new int[] {}));
System.out.println(sumOfPositives(new int[] { 5 }));
System.out.println(sumOfPositives(new int[] { 3, 4 }));
System.out.println(sumOfPositives(new int[] { -2, 3, -4 }));
System.out.println(sumOfPositives(new int[] { -1, -2, -4, -5 }));
System.out.println(sumOfPositives(new int[] { 6, 1, 2, -3, 8 }));
}
private static int sumOfPositives(int[] list) {
return list.length == 0 ? 0 : sumOfPositives(list, 0, 0);
}
private static int sumOfPositives(int[] list, int index, int total) {
if (list[index] > 0) {
total++;
}
if (index + 1 < list.length) {
return sumOfPositives(list, index + 1, total);
}
return total;
}
}
热门问题