粗糙双二维阵列的平均



我的Java编码课的作业是让我找到双二维数组和整数二维数组的粗糙二维数组的平均值。我相信我的代码是正确的但它不是对数组求平均值,而是将它除以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)

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

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

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

这就是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;
}

}

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

相关内容

  • 没有找到相关文章

最新更新