java - 如何在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;
}
解决方案
//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;
}
推荐阅读
- python - keras 总是直线预测
- php - 从未知格式/Date(1576648800000)/在php中格式化日期
- python - python axes.ravel() IndexError:数组索引过多
- python - Python - 比较两个数据帧之间的范围
- python - 从python中的文本文件导入输入
- swift - swift 如何从我们在文档目录中创建的子文件夹中获取所有文件?
- java - 如何从 cxf outInterceptor 获取响应正文
- javascript - 拉动刷新不会在特定屏幕上禁用(React js)
- c++ - Qt没有完整的头文件是有原因的吗?
- c++ - 从函数返回向量以打印内容