如何在java中求和矩阵行?

时间:2015-10-13 02:13:02

标签: java matrix

当我创建二维矩阵时,如下所示:

22 21 36  -------> 22+21+36 = 79/3 = 26
22 18 18  
32 27 43  
 7 10  4  
29 27 35  
26 17 24  
14 25 30  
29 23 36  
15 21  8  
13 16 33  

如何在Java中将行的总和除以3?

2 个答案:

答案 0 :(得分:0)

要解决此问题,一般要考虑您有一个维度矩阵nrow x ncol

float[][] mat = new float[nrow][ncol];
float ave = 0;

// Fill the matrix with values ...
// ...
//

for (int irow=0; irow<nrow; ++irow) {   // For every row...
  for (int icol=0; icol<ncol; ++icol) { // ... and every column
    ave += mat[irow][icol]              // Sum up the values of this row
  }
  ave /= ncol;                          // Divide by number of columns

  // Do something with this value.
}

答案 1 :(得分:0)

public class Driver {

    public static void main(String[] args) {
        // this is your matrix minus some rows
        int[][] matrix = { {22, 21, 36},
                           {22, 18, 18},
                           {32, 27, 43}
                         };
        int rowSum; // used to sum each row
        int divByThree = 0; // used to divide each sum by three

        // iterate over each row in the matrix
        for(int row = 0; row < matrix.length; row++) {
            rowSum = 0; // reset rowSum to zero to sum the next row

            // iterate over each column in the matrix
            for(int col = 0; col < matrix[row].length; col++) {
                System.out.print(matrix[row][col] + " ");

                rowSum += matrix[row][col]; // add the value at position (row, col)
            }

            System.out.print("= " + rowSum + " / 3 = ");

             // divide rowSum by 3, divByThree is an integer so everything
             // after the decimal point will be chopped off
            divByThree = rowSum / 3;

            System.out.print(divByThree + "\n");
        }
    }

}

<强>输出:

22 21 36 = 79 / 3 = 26
22 18 18 = 58 / 3 = 19
32 27 43 = 102 / 3 = 34