粗糙的双二维数组的平均值

时间:2013-05-01 22:32:58

标签: java multidimensional-array average

我的java编码类的作业要求我找到一个双重2d数组和整数2d数组的参差不齐的二维数组的平均值。我相信我的代码是正确的,但不是平均数组,而是将它除以2.任何帮助都将不胜感激!

代码:

public static void main(String[] args) {
    // adds to 22
    double[][] a = {{7.0, 6.0, 5.0}, {3.0, 1.0}};

   //adds to 48
    int[][] b = {{4, 6}, {9, 8, 10, 11}};
    int i = 0;
    System.out.println("arrayAverage = " + arrayAverage(a));
    System.out.println("arrayAverage = " + arrayAverage(b));
}

/**
 * computes the average for an array of a double
 */
public static double arrayAverage(double a[][]) {
    double sum = 0.0;

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            sum += a[i][j];

        }

    }

    System.out.println("Calculating Double Array");
    return sum / a.length;
}
/**
 * Computes the average for an array of integers.
 */
public static int arrayAverage(int b [][]) {
    int sum = 0;

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b[i].length; j++) {
            sum += b[i][j];

        }

    }

    System.out.println("Calculating Integer Array");
    return sum / b.length;
}

}

run:
Calculating Double Array
arrayAverage = 11.0
Calculating Integer Array
arrayAverage = 24
BUILD SUCCESSFUL (total time: 0 seconds)

2 个答案:

答案 0 :(得分:2)

除以a.length时,除以2,因为这是数组a的长度。数组a中有两个项目:{7.0, 6.0, 5.0}{3.0, 1.0}

要平均数组中的所有数字,您需要通过总结子数组的长度来计算所有数字。声明count变量,并在i for循环中,向其添加子数组a[i].length的长度。然后在结尾处除以count

int[][]整数除法的平均方法中要小心,其中小数被截断。

答案 1 :(得分:0)

这就是rgettman的意思

    public static void main(String[] args) {

        double[][] a = {{7.0, 6.0, 5.0}, {3.0, 1.0}};
        int[][] b = {{4, 6}, {9, 8, 10, 11}};
        System.out.println("arrayAverage = " + arrayAverage(a));
        System.out.println("arrayAverage= " + arrayAverage(b));

    }


/**
 * computes the average for an array of a double
 */
public static double arrayAverage(double a[][]) {

    double sum = 0.0;
    int count = 0; 

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            sum += a[i][j];
            count++;

        }

    }

    System.out.println("Calculating Double Array");

    return sum / count;
}





/**
 * Computes the average for an array of integers.
 */
public static int arrayAverage(int b [][]) {
    int sum = 0;
    int count = 0; 

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b[i].length; j++) {
            sum += b[i][j];
            count++;


        }

    }

    System.out.println("Calculating Integer Array");
    return sum / count;
}


}

你应该得到正确答案:)