【问题标题】:Multiplying 2d arrays(matrices) in java在java中乘以二维数组(矩阵)
【发布时间】:2013-04-11 02:01:07
【问题描述】:

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

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

}
}

感谢您的帮助。

【问题讨论】:

    标签: java arrays multidimensional-array matrix


    【解决方案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("");
    }
    

    【讨论】: