2D阵列平均值(Java)

时间:2014-11-20 22:08:56

标签: java for-loop average multidimensional-array

我需要这个方法来获取在其他方法中创建/更改的2D数组的中间列,计算每行的平均值(不包括0索引和最后一个索引),将该平均值放在最后一列中行,然后转到下一行并重复,直到没有更多行。基本上,2行3列的设置实际上有5列,如下所示。

   Weight  Grade1  Grade2  Grade3  Average
  ----------------------------------------
1|  4.0     5.0     5.0     5.0    -999.0  
2|  5.0     10.0    10.0    10.0   -999.0  

该方法需要获取成绩分数,找到它们的平均值,然后用平均值替换-999.0,然后对存在的下一行(在另一个方法中由用户输入定义的大小)执行相同操作。这是我的方法代码,我知道我非常接近,但我在某处犯了一些错误。

public static double[][] computeCategoryAverages(double[][] scoreArray){
    for(int i = 0; i < scoreArray.length; i++){
        double sum = 0;
        int numOfAssign = 0;
        if(i == 0){
            System.out.println("The Average for the first category: ");
            for(int j = 1; j < scoreArray[0].length-1; j++){
                sum = sum + scoreArray[0][j];
                numOfAssign++;
            }
            double average = sum / numOfAssign;

            for(int k = 0; k < scoreArray.length; k++){
                //sum = sum + scoreArray[i][j];
                //noOfAssign++;     
                scoreArray[k][scoreArray[k].length-1] = average;  
            }
        }
        else{
            System.out.println("The Average for the next category: ");
            for(int j = 1; j < scoreArray[0].length-1; j++){
                sum = sum + scoreArray[i][j];
                numOfAssign++;
            }
            double average = sum / numOfAssign;
            for(int k = 0; k < scoreArray.length; k++){
                //sum = sum + scoreArray[i][j];
                //noOfAssign++;     
                scoreArray[k][scoreArray[k].length-1] = average;  
            }
        }
    }
    return scoreArray;
}

2 个答案:

答案 0 :(得分:2)

我无法完全理解您的代码。如果你能评论它会很棒。但在那里我会给你一个伪代码(ish),我希望这会以某种方式帮助你。 假设: 你的数组是双

double tempSum=0;

for (int x = 0; x < amount of rows; x++)
{
   tempSum=0;

   for(int y = 1(because excluding first index); y < amount of numbers - 1 (because excluding last; y++)
   {
       tempSum+= marks[x][y];
   }
   marks[x][length-1]=(tempSum/length-2) //setting the average to the last index, length -2 to account for index 0 and last one
}

然后根据需要输出

你的代码似乎有点太复杂了所需要的东西= p

答案 1 :(得分:2)

试试这个:

public static double[][] computeCategoryAverages(double[][] scoreArray){
for(int i = 0; i < scoreArray.length; i++){
    double sum = 0;
    int numOfAssign = 0;
    double average=0.0;
    System.out.printf("The Average for category:%d:",i+1);
    for(int j = 1; j < scoreArray[i].length-1; j++){
       numOfAssign++;
       sum = sum + scoreArray[i][j];

      }
    double average = sum / numOfAssign;
    scoreArray[i][scoreArray[i].length-1] = average;  

}
return scoreArray;
}
相关问题