题解 | #矩阵乘法#
矩阵乘法
https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int a = in.nextInt(); //这种没法从原理优化算法的题尽量写工整点可读性强 int b = in.nextInt(); int c = in.nextInt(); int[][] arr1 = new int[a][b]; int[][] arr2 = new int[b][c]; int[][] ans = new int[a][c]; for (int i = 0; i < a; i++) { //输入矩阵1 for (int j = 0; j < b; j++) { arr1[i][j]=in.nextInt(); } } for (int i = 0; i < b; i++) { //输入矩阵2 for (int j = 0; j < c; j++) { arr2[i][j]=in.nextInt(); } } //高等数学 离散数学 都学过吧 for (int i = 0; i < a; i++) { //最外层大循环遍历矩阵1行数 for (int j = 0; j < c; j++) { //中间层循环遍历矩阵2列数 for (int h = 0; h < b; h++) { //最里层循环遍历矩阵1列数和矩阵2行数 ans[i][j] += arr1[i][h] * arr2[h][j];//求元素积之和输入到新矩阵里 } } } for (int i = 0; i < a; i++) { //输出答案 for (int j = 0; j < c; j++) { System.out.print(ans[i][j] + " "); } System.out.println(); } } } }