我的 Java 编码课程的作业是要求我找到双 2d 数组和整数 2d 数组的参差不齐的二维数组的平均值。我相信我的代码是正确的,但不是平均数组,而是将其除以 2。任何帮助将不胜感激!
代码:
public static void main(String[] args) {
// adds to 22
double[][] a = {{7.0, 6.0, 5.0}, {3.0, 1.0}};
//adds to 48
int[][] b = {{4, 6}, {9, 8, 10, 11}};
int i = 0;
System.out.println("arrayAverage = " + arrayAverage(a));
System.out.println("arrayAverage = " + arrayAverage(b));
}
/**
* computes the average for an array of a double
*/
public static double arrayAverage(double a[][]) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
sum += a[i][j];
}
}
System.out.println("Calculating Double Array");
return sum / a.length;
}
/**
* Computes the average for an array of integers.
*/
public static int arrayAverage(int b [][]) {
int sum = 0;
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
sum += b[i][j];
}
}
System.out.println("Calculating Integer Array");
return sum / b.length;
}
}
run:
Calculating Double Array
arrayAverage = 11.0
Calculating Integer Array
arrayAverage = 24
BUILD SUCCESSFUL (total time: 0 seconds)