我有以下学校作业: public static double sum(double [] a, int low, int high)
返回数组切片 a[low:high] 中所有数字的总和。
如果低 > 高,则抛出 IllegalArgumentException。否则,它检查是否 该切片有 1 项。如果是,则返回该值。
如果切片有 2 个或更多项目,它将切片分为 2 个相等的子切片,计算总和 2 个子切片的并返回 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
不太正确。 (想想如果低
= 98且高
= 100会发生什么。)当你递归时,你需要记住你传递的索引包含,所以在第二个递归调用中我建议你将 1 添加到较低的索引(这样它就不会不与第一个递归调用的上索引重叠)
如果您希望我澄清其中任何一项,请告诉我。
关于java - 递归求数组元素之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28932314/