import java.util.Scanner;
public class juzhen {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("请输入第一个矩阵的二维数据:");
int n1 = in.nextInt();
int m1 = in.nextInt();
int[][] a = new int[n1][m1];
for (int i = 0; i < n1; i++) { // 循环输入第一个矩阵
for (int j = 0; j < m1; j++) {
a[i][j] = in.nextInt();
}
}
System.out.print("请输入第二个矩阵的二维数据:");
int n2 = in.nextInt();
int m2 = in.nextInt();
int[][] b = new int[n2][m2];
for (int i = 0; i < n2; i++) { // 循环输入第二个矩阵
for (int j = 0; j < m2; j++) {
b[i][j] = in.nextInt();
}
}
System.out.print("输出矩阵相乘后的矩阵:" + "\n");
for (int[] h : xcheng(n1, m2, n2, a, b)) {
for (int h1 : h) {
System.out.print(h1 + " ");
}
System.out.println();
}
in.close();
}
static int[][] xcheng(int q, int w, int e, int[][] q1, int[][] q2) {
int[][] c = new int[q][w]; // 从 he 函数提取计算后的数字,逐个赋值到c数组,返回c数组
for (int i = 0; i < q; i++) {
for (int j = 0; j < w; j++) {
c[i][j] = he(i, j, e, q1, q2);
}
}
return c;
}
static int he(int a1, int a2, int a3, int[][] q2, int[][] q3) { // 实现矩阵相乘的每一位数字的计算
int ooo = 0;
for (int i = 0; i < a3; i++) {
ooo += q2[a1][i] * q3[i][a2];
}
return ooo;
}
}
|