如何计算二维数组中每一列的平均值? [英] How to calculate the average value of each column in 2D array?
本文介绍了如何计算二维数组中每一列的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试计算2D数组中列的平均值,但是我无法弄清楚代码.该函数应返回每列的平均值.而且我无法在函数中打印结果.打印应该在主要功能中.
I am trying to calculate the average value of columns in 2D array, but I cannot figure out the code. The function should return the average value of each column. And I cannot print the result in the function. The print should be in main function.
static double average_columns(double matrix[][]) {
int i, j, sum = 0, average=0;
for (i = 0; i < matrix.length; i++) {
for (j = 0; j < matrix[i].length; j++) {
sum=(int) (sum+matrix[i][j]);
}
average=sum/matrix[i].length;
sum=0;
}
return average;
}
推荐答案
You can use Stream.reduce
method to summarise the elements in columns and then divide each sum by the number of columns:
double[][] matrix = {
{1.11, 2.22, 3.33, 4.45, 5.56},
{6.61, 7.76, 8.88, 9.9, 10.11},
{11.1, 12.2, 13.3, 14.4, 15.5},
{16.6, 17.7, 18.8, 19.9, 20.0},
{21.1, 22.2, 23.3, 24.4, 25.5}};
double[] average = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) ->
// iterate over the indices
// from 0 to row length
IntStream.range(0, row1.length)
// summarize in pairs the
// elements of two rows
.mapToDouble(i -> row1[i] + row2[i])
// an array of sums
.toArray())
// stream containing
// the resulting array
// Stream<double[]>
.stream()
// iterate over the array of sums
// Stream<double[]> to DoubleStream
.flatMapToDouble(Arrays::stream)
// divide each element by
// the number of columns
.map(i -> i / matrix.length)
.toArray();
System.out.println(Arrays.toString(average));
// [11.304, 12.416, 13.522, 14.61, 15.334]
另请参见:将2d数组中每一列的所有元素相加
这篇关于如何计算二维数组中每一列的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文