0

我的目标是在两个数组相乘时打印出矩阵。我对这段代码做错了什么?我如何得到它以便打印出矩阵?(对不起,我不知道我应该提供哪些其他细节,除非我添加更多细节,否则我无法提交这篇文章)。

public class Matrices {
static int mRows = 0;
static int mCol = 0;
static int nRows = 0;
static int nCol = 0;
 public static int[][] multiplyMatrices(int[][] m, int[][] n){
    mRows = m.length;
    mCol = m[0].length;
    nRows = n.length;
    nCol = n[0].length;
    if(canBeMultiplied(m,n) == false){
        throw new IllegalArgumentException("Cannot multiply arrays");
    }
    int[][] answer = new int[mRows][nCol];
    for(int i = 0; i < mRows; i++){
        for(int j = 0; j < nCol; j++){
            for(int k = 0; k < mCol; k++){
                answer[i][j] += m[i][k] * n[k][j];
            }
        }
    }
    return answer;
}

public static boolean canBeMultiplied(int[][] m, int[][]n){
    mRows = m.length;
    mCol = m[0].length;
    nRows = n.length;
    nCol = n[0].length;
    if(nRows == mCol){
        return true;
    }
    return false;
}

public static void main(String[] args) {
    int[][] temp1 = {{1,2,3},{4,5,6}};
    int[][] temp2 ={{1},{2},{3}};
    for(int i = 0; i < mRows; i++){
        for(int j = 0; j < nCol; j++){
            System.out.print(multiplyMatrices(temp1,temp2)[i][j]);
        }
                    System.out.print("\n");
    }

}
}

谢谢你的帮助。

4

1 回答 1

1

这可能会遍历二维数组并打印每个元素。

static final int ROWS = 2;
static final int COLS = 4;

int[][] a2 = new int[ROWS][COLS];

//... Print array in rectangular form
for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLS; j++) {
        System.out.print(" " + a2[i][j]);
    }

    System.out.println("");
}
于 2013-04-11T02:03:50.583 回答