可以使用Java中的可变参数来编写一个只需要一个方法即可计算任意数量数组的平均值的函数:
Copy code
public static double a1(double[]... arrays) {
double sum = 0;
int count = 0;
for (double[] array : arrays) {
for (double value : array) {
sum += value;
count++;
}
}
return sum / count;
}
然后可以使用以下代码来调用该方法,并将结果赋给对应的变量:
Copy code
double a2, b2, c2, d2;
double a[] = {90, 85, 66, 51, 69, 78, 88, 94};
double b[] = {68, 88, 81, 90, 65, 74, 64, 46};
double c[] = {68, 90, 85, 88, 68, 70};
double d[] = {60};
a2 = b2 = c2 = d2 = a1(a, b, c, d);
这样就可以使用一次方法调用计算所有数组的平均值了。
这样应该行
public class Test20
{
public static double[] a1(double[]...a)
{
double[] suma=new double[a.length];
for(int i=0;i
for(int j=0;j sum+=a[i][j];
if(j==(a[i].length-1)){
suma[i]=sum/a[i].length;
}
}
}
return suma;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
double a2;
double b2;
double c2;
double d2;
double a[]={90,85,66,51,69,78,88,94};
double b[]={68,88,81,90,65,74,64,46};
double c[]={68,90,85,88,68,70};
double d[]={60};
double[] avg=a1(a,b,c,d);
a2=avg[0];
b2=avg[1];
c2=avg[2];
d2=avg[3];
System.out.println(a2+","+b2+","+c2+","+d2);
}
}