【问题标题】:Calculate averages of rows in a data table using arrays in Java使用 Java 中的数组计算数据表中行的平均值
【发布时间】:2017-10-28 00:46:05
【问题描述】:

我正在尝试计算行和列的平均值。所以,到目前为止,我可以获得列的平均值,但是,我很难计算行的平均值。

我有这样的数据表,

Example1      Example2    Example2  
 85              75         92
 80              91         89
 85              52         78

到目前为止,我正在做的是将它们每一列作为一个数组,如下所示:

int[] Example1 = {85, 80, 85};
int[] Example2 = {75, 91, 52};
int[] Example3 = {92, 89, 78};

然后我创建了一个这样的方法(计算表中每一列的平均值),

public static void avg_calc(int[] examples) { 
    int sum = 0;
    int avg;
    for (int i = 0; i < examples.length; i ++) {
        sum += examples[i];
    }
    avg = sum/examples.length;
    System.out.println("Average is " + avg);
}   

这样,当我执行avg_calc(Example1) 时,我可以计算'Example1` 数组的平均值,即83。

但是,我想计算 Example1Example2Example3 的平均值,例如,第一行的平均值为 84。

如何在函数中添加另一个数组来计算行的平均值?

任何帮助将不胜感激。

【问题讨论】:

    标签: java arrays methods


    【解决方案1】:

    如何在我的函数中添加另一个数组来计算平均值 行吗?

    一种方法:

        int[] Example1 = {85, 80, 85};
        int[] Example2 = {75, 91, 52};
        int[] Example3 = {92, 89, 78};
        int[][] examples = {Example1, Example2, Example3}; // new array
    
        for (int i = 0; i < examples[0].length; i++) {
            double rowAverage = 0;
            for (int[] arr : examples) {
                    rowAverage += arr[i];
            }
            System.out.println("Average of row " + (i + 1) + ": " + rowAverage / examples.length);
        }        
    

    输出

    Average of row 1: 84.0
    Average of row 2: 86.66666666666667
    Average of row 3: 71.66666666666667
    

    【讨论】:

    • 太好了,我将int[][] Examples 添加到我的方法中,并像您一样通过示例迭代创建。当我通过avg_calc(Example1, Examples) 时,我会在每列的平均值下重复行平均值。我想我必须修改我的打印语句。
    • 我实际上更喜欢@Paul Lemarchand 的回答:这样您就可以编写一个计算行(索引)平均值的方法 - 并将其称为您需要它的次数。它最终成为更加模块化的 IMO。
    【解决方案2】:

    @alfasin 的回答很棒,这是一个 java 8 解决方案:

    public static int getRowAverage(int index, int[]... examples) {
        return Arrays.stream(examples)
                .mapToInt(ex -> ex[index]).sum() / examples.length;
    
    }
    

    你可以试试:

    public static void main(String[] args) {
        int[] example1 = {85, 80, 85};
        int[] example2 = {75, 91, 52};
        int[] example3 = {92, 89, 78};
        // for row 1 (index 0)
        int average_row_1 = getRowAverage(0, example1, example2, example3);
        System.out.println(average_row_1);
    }
    

    【讨论】:

    • 您可以通过利用 mapToInt 中的 lambda 使其更短:Arrays.stream(examples).mapToInt(arr -&gt; arr[index]).sum() / examples.length;
    • @PaulLemarchand 谢谢你,这似乎是一个不错的答案,作为一个 Java 新手,这对我来说似乎有点先进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多