java 如何在二维数组JAVA中找到元素的平均值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40709464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:25:48  来源:igfitidea点击:

How to find average of elements in 2d array JAVA?

javaarrays2d

提问by E. Hazard

I need help with the following program:

我需要以下程序的帮助:

"Write a method that will take a two-dimensional array of doubles as an input parameter & return the average of the elements of the array."

“编写一个方法,将二维数组作为输入参数并返回数组元素的平均值。”

Can anyone tell me how to go about it?

谁能告诉我该怎么做?

My current code:

我目前的代码:

public static double average(float arr[][]) {
double sum = 0;
int count = 0;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[0].length; col++) 
{
sum += arr[row][col];
count++;
}
return sum/count;
}

I don't know how to let the user input the array elements and array dimensions (row/columns). Also how do I call this method from main? I am getting errors.

我不知道如何让用户输入数组元素和数组维度(行/列)。另外我如何从main调用这个方法?我收到错误。

回答by user6904265

If you want to to all in one line (two-dimensional intarray):

如果你想在一行(二维int数组):

Arrays.stream(array).flatMapToInt(Arrays::stream).average().getAsDouble();

If you deal with a two-dimensional doublearray:

如果你处理一个二维double数组:

Arrays.stream(array).flatMapToDouble(Arrays::stream).average().getAsDouble();

回答by Dani

try this:

试试这个:

Code:

代码:

public class AverageElements {
    private static double[][] array;

    public static void main (String[] args){

        //  Initialize array
        initializeArray();

        //  Calculate average
        System.out.println(getAverage());
    }   

    private static void initializeArray(){
        array = new double[5][2];
        array[0][0]=1.1;
        array[0][1]=12.3;
        array[1][0]=3.4;
        array[1][1]=5.8;
        array[2][0]=9.8;
        array[2][1]=5.7;
        array[3][0]=4.6;
        array[3][1]=7.45698;
        array[4][0]=1.22;
        array[4][1]=3.1478;
    }

    private static double getAverage(){
        int counter=0;
        double sum = 0;
        for(int i=0;i<array.length;i++){
            for(int j=0;j<array[i].length;j++){
                sum = sum+array[i][j];
                counter++;
            }
        }

        return sum / counter;
    }
}

Output:

输出:

5.452478000000001

回答by mincoder

Since you asked so nicely! Here is the code:

既然你问得这么好!这是代码:

public double Averagearray(double[][] array) {
    double total=0;
    int totallength;
    for(int i=0;i<array.length;i++) {
        for(int j=0;j<array[i].length;j++) {
            total+=array[i][j];
            totallength++;
        }
    }
    return total/(totallength);
}