首页 > 解决方案 > 如何在java中显示从方法到主方法的两个矩阵的总和?

问题描述

如何在java中显示从方法到主方法的两个矩阵的总和?

public static void main(String [] args) {

int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;

int [][] matrix1 = new int[ir1][ic1];

int [][] matrix2 = new int[ir2][ic2];

  int[][] total = add (matrix1, matrix2);

   System.out.println("\nThe addition of two Matrices: ");

        for (int r = 0; r < total.length; r++) {
          for (int c = 0; c < total[r].length; c++)
                 System.out.printf("%7d", total[r][c]);
               System.out.println();
        }
}

public static int [][] add (int[][] m1, int[][] m2) {

      int ir1 = 0, ic1 = 0;

      int total[][] = new int [ir1][ic1];

      for (int r = 0; r < m1.length; r++) {
        for (int c = 0; c < m2[r].length; c++) {
          total [r][c] = m1[r][c] + m2[r][c];
        }
      }
      return total;
}

标签: javamultidimensional-arraymethods

解决方案


//Assuming both array will have same dimensions.

public static int [][] add (int[][] m1, int[][] m2) {
  
  int ir1 = m1.length, ic1 = m1[0].length;
  int total[][] = new int [ir1][ic1];

  for (int r = 0; r < ir1; r++) {
    for (int c = 0; c < ic1; c++) {
      total [r][c] = m1[r][c] + m2[r][c];
    }
  }
  return total;
}

推荐阅读