java多个数组的平均值
时间: 2023-12-20 19:49:39 浏览: 81
如果你要计算多个数组的平均值,你需要先将这些数组合并成一个大数组,然后再计算平均值。
以下是一个示例代码:
```java
public class AverageOfMultipleArrays {
public static void main(String[] args) {
int[] arr1 = {2, 4, 6};
int[] arr2 = {1, 3, 5};
int[] arr3 = {8, 10, 12};
int[] mergedArr = mergeArrays(arr1, arr2, arr3);
double avg = calculateAverage(mergedArr);
System.out.println("The average value of the merged array is: " + avg);
}
// 合并多个数组
public static int[] mergeArrays(int[]... arrays) {
int totalLength = 0;
for (int[] array : arrays) {
totalLength += array.length;
}
int[] mergedArray = new int[totalLength];
int destPos = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, mergedArray, destPos, array.length);
destPos += array.length;
}
return mergedArray;
}
// 计算平均值
public static double calculateAverage(int[] arr) {
int sum = 0;
for (int i : arr) {
sum += i;
}
return (double) sum / arr.length;
}
}
```
输出结果:
```
The average value of the merged array is: 6.0
```
阅读全文