2 回答
TA贡献1873条经验 获得超9个赞
要找到哪个子数组的平均值更大,您必须计算它们并保持 max :
public static void main(String[] args){
int array1[][] = {{90, 80, 65, 100}, {55, 94, 86}, {82}, {77, 100}};
double maxAverage = Double.MIN_VALUE;
for(int[] sub : array1){ //iterate over sub-arrays
double average = averageOfArray(sub); //compute its average
maxAverage = Math.max(maxAverage, average);//get the max of it and the previous max
}
System.out.printn(maxAverage)
}
static double averageOfArray(int[] array){
double sum = 0;
for(int i=0; i<array.length; i++){
sum += array[i];
}
return sum/array.length;
}
或作为 Java 8 升级方式:
int array1[][] = {{90, 80, 65, 100}, {55, 94, 86,}, {82}, {77, 100}};
double maxAverage = Arrays.stream(array1).mapToDouble(sub -> Arrays.stream(sub).average().orElse(0)).max().orElse(0);
System.out.println(maxAverage)
TA贡献1906条经验 获得超3个赞
当您需要对数组进行字符串化时,您可以使用Arrays.toString(arr); 对于多维数组,您应该使用 Arrays.deepToString(arr);
int array1[][] = {{90, 80, 65, 100}, {55, 94, 86,}, {82}, {77, 100}};
System.out.println(Arrays.deepToString(array1));
[[90, 80, 65, 100], [55, 94, 86], [82], [77, 100]]
添加回答
举报