1

我的 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)
4

2 回答 2

2

当除以时a.length,您正在除以2,因为那是数组的长度a。数组中有两项a{7.0, 6.0, 5.0}{3.0, 1.0}

要平均数组中的所有数字,您需要通过对子数组的长度求和来计算所有数字。声明一个count变量,并在ifor 循环中添加子数组的长度a[i].length。然后在最后除以count

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

于 2013-05-01T22:37:33.267 回答
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;
}


}

你应该得到正确的答案:)

于 2013-05-02T09:57:06.703 回答