問題描述
小明最近剛剛學習了矩陣乘法,但是他計算的速度太慢,於是他希望你能幫他寫一個矩陣乘法的運算器。
輸入格式
輸入的第一行包含三個正整數N,M,K,表示一個NM的矩陣乘以一個MK的矩陣。接下來N行,每行M個整數,表示第一個矩陣。再接下來的M行,每行K個整數,表示第二個矩陣。
輸出格式
輸出有N行,每行K個整數,表示矩陣乘法的結果。
樣例輸入
2 1 3
1
2
1 2 3
樣例輸出
1 2 3
2 4 6
思路:藍橋官網對這個矩陣乘法已經出過好幾次這樣子的題目了,老規矩,捋清楚輸入的部分,兩個數組相乘得出第三個數組,就可。
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int s = scanner.nextInt();
int[][] arr = new int[n][m]; // 第一個數組
int[][] brr = new int[m][s]; // 第二個數組
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = scanner.nextInt(); // 保存第一個數組輸入內容
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < s; j++) {
brr[i][j] = scanner.nextInt(); // 保存第二個數組輸入內容
}
}
int[][] crr = new int[n][s]; // 第三個數組
for (int i = 0; i < n; i++) {
for (int j = 0; j < s; j++) {
crr[i][j] = 0; // 初始值爲0
for (int k = 0; k < m; k++) {
crr[i][j] += arr[i][k] * brr[k][j]; // 3+=1*2
}
System.out.print(crr[i][j] + " "); // 輸出
}
System.out.println(); // 換行
}
}
}