【发布时间】:2015-03-08 21:51:13
【问题描述】:
我有以下学校作业: 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());
}
}
【问题讨论】:
-
嗯,你试过运行你写的东西吗?