简体   繁体   English

如何乘以2D数组的列? 爪哇

[英]How do I multiply columns of a 2D array? Java

Previous methods construct and fill a 2D double array with a size defined by user input. 先前的方法使用用户输入定义的大小构造和填充2D双精度数组。 computeCategoryAverages takes the middle indexes, averages them, then puts them in the final index computeOverallAverage is then supposed to multiply the 0 index (weight) by the final index and store that number, then repeat till the rows end, adding each time. computeCategoryAverage取中间索引,取其平均值,然后将其放入最终索引中。computeOverallAverage然后应将0索引(权重)乘以最终索引并存储该数字,然后重复进行直到行结束,每次都相加。

   Weight  Grade1  Grade2  Grade3  Average
  ----------------------------------------
1| 3.0  456.0  4356.0  456.0    1756.0  
2| 4.0  3456.0 674.0  34534.0  12888.0
3| 2.0  236.0  791.0   536.0    521.0

Example of what computeOverallAverage is supposed to do:
3.0 * 1756.0 = 5268
4 * 12888.0 = 51552
5268 + 51552= 56820
2 * 521= 1042
56820 + 1042 = 57862

computeCategoryAverages works flawlessly. computeCategoryAverages可以完美地工作。

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);
        System.out.println();
        for(int j = 1; j < scoreArray[i].length-1; j++){
            numOfAssign++;
            sum = sum + scoreArray[i][j];
        }
        average = sum / numOfAssign;
        scoreArray[i][scoreArray[i].length-1] = average;  
    }    
    return scoreArray;
}

The issues i'm having is with the computeOverallAverage, i'm not really sure how to make the arrays function properly with loops to multiply the columns and compound them with additiion. 我遇到的问题是computeOverallAverage,我不太确定如何使数组通过循环正确运行,以使列相乘并将其与加法复合。

// Compute the overall average
public static double computeOverallAverage(double[][] scoreArray){
    double currentAverage = 0;
    for(int i = 0; i < scoreArray[i].length-1; i++){
        //(weightedAverage = average *weight);
        double wAverage = scoreArray[i][scoreArray[i].length-1] * scoreArray[i][0];
        currentAverage += wAverage;

    }
    return currentAverage;
}

in your for loop in computeOverAllAverage computeOverAllAverage的for循环中

remote the index scoreArray[i].length 远程索引scoreArray[i].length

scoreArray.length = length of rows scoreArray[i].length = length of columns scoreArray.length =行的长度scoreArray[i].length =列的长度

in your for loop you want to loop for the rows. 在您的for循环中,您要循环查看行。

 for(int i = 0; i < scoreArray.length-1; i++){
        //(weightedAverage = average *weight);
        double wAverage = scoreArray[i][scoreArray[i].length-1] * scoreArray[i][0];
        currentAverage += wAverage;

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM