2013-05-01 73 views
1

我的java编码类的作业是要求我找到一个双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

当由a.length分割,则通过2分割,因为这是阵列a的长度。数组a中有两个项目:{7.0, 6.0, 5.0}{3.0, 1.0}

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

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

+0

你通过一个计数变量是什么意思? – user2313658 2013-05-02 01:26:25

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; 
} 


} 

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

+0

谢谢你的帮助! – user2313658 2013-05-02 17:48:57

相关问题