【问题标题】:Calculate the average of this two dimensional array计算这个二维数组的平均值
【发布时间】:2019-02-04 18:42:16
【问题描述】:

我现在正在寻找的是一种打印此代码第二行平均值的方法。

import java.util.Scanner;
public class MojaLoi{
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);

    int [][] a = new int[6][6];

    for(int i=0; i<a.length; i++){
        for(int j=0; j<a[i].length; j++){
            a[i][j] = sc.nextInt();
        }
    }
    for(int i=0; i<a.length; i++){
        for(int j=0; j<a[i].length; j++){
            System.out.print(a[i][j]+" ");
        }
        System.out.println();
    }
}

非常感谢任何回复。

【问题讨论】:

    标签: java arrays multidimensional-array average


    【解决方案1】:

    要计算第二行的平均值,请使用:

    float sum = 0;
    for(int j=0; j<a[0].length; j++){
        sum += a[1][j];   // i = 1 for second row
    }
    float average = sum / a[0].length;
    System.out.println(average);
    

    【讨论】:

    • 例如,如果这是我的数组 {{1 2 3 4 5 6}, {7 8 9 10 11 12}, {13 14 15 16 17 18}, {19 20 21 22 23 24 }, {25 26 27 28 29 30}, {31 32 33 34 35 36} 然后我想打印第二行的平均值 {7,8,9,10,11,12}
    • 非常感谢,正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多