任务描述
本关任务:编写一个程序,输入两个矩阵输出矩阵乘的结果。
矩阵乘法
矩阵相乘最重要的方法是一般矩阵乘积。它只有在第一个矩阵的列数( column )和第二个矩阵的行数( row )相同时才有意义。
矩阵乘法的定义如下:
设A
为 m×p
的矩阵,B
为 p×n
的矩阵,那么称 m×n
的矩阵C
为矩阵A
与B
的乘积,记作AB
,其中矩阵C
中的第 i
行第 j
列元素可以表示为:
矩阵乘法示例
编程要求
根据提示,在右侧编辑器补充代码,依次输入两个整数矩阵,输出矩阵乘法的结果,在输入矩阵时,先输入行列数,再输入矩阵。
测试说明:
平台会对你编写的代码进行测试:
测试输入:
3 2
1 2
3 4
5 6
2 4
1 2 3 4
5 6 7 8
预期输出:
11 14 17 20
23 30 37 44
35 46 57 68
完成代码:
import java.util.Scanner;
public class Multiply {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] result = null;
//请在指定位置填写代码。
/********* Begin *********/
int a1 = input.nextInt();
int a2 = input.nextInt();
int a[][] = new int[a1][a2];
for(int i = 0; i < a1; i++) {
for(int j = 0; j < a2; j++) {
a[i][j] = input.nextInt();
}
}
int b1 = input.nextInt();
int b2 = input.nextInt();
int b[][] = new int[b1][b2];
for(int i = 0; i < b1; i++) {
for(int j = 0; j < b2; j++) {
b[i][j] = input.nextInt();
}
}
int x = a.length;
int y = b[0].length;
result = new int[x][y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
for (int k = 0; k < b.length; k++)
result[i][j] += a[i][k] * b[k][j];
/********* End *********/
for(int i = 0; i < result.length; i++){
for(int j = 0; j < result[i].length; j++){
System.out.print(String.format("%d ", result[i][j]));
}
System.out.println();
}
}