题解 | #矩阵乘法#
矩阵乘法
https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b
单独解耦了行列乘积和
import java.util.Arrays; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static int sum(int[] m1, int[] m2){ int res = 0; for(int i=0;i<m1.length;i++) res += m1[i]*m2[i]; return res; } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int x = in.nextInt(),y = in.nextInt(),z = in.nextInt(); int matrix1[][] = new int[x][y]; int matrix2[][] = new int[y][z]; int res[][] = new int[x][z]; for(int i=0;i<x;i++) for(int j=0;j<y;j++) matrix1[i][j] = in.nextInt(); for(int i=0;i<y;i++) for(int j=0;j<z;j++) matrix2[i][j] = in.nextInt(); for(int i=0;i<x;i++){ for(int j=0;j<z;j++){ int finalJ = j; int[] m2 = Arrays.stream(matrix2).mapToInt(row->row[finalJ]).toArray(); res[i][j] = sum(matrix1[i],m2); } } for(int[] row : res){ for(int i : row)System.out.print(i+" "); System.out.print("\n"); } } }