题目描述
如果A是个x行y列的矩阵,B是个y行z列的矩阵,把A和B相乘,其结果将是另一个x行z列的矩阵C。这个矩阵的每个元素是由下面的公式决定的:原型:voidmatrix_multiply(int *m1,int *m2,int *r, int x, int y, int z);输入参数: int *m1:x行y列的矩阵(array1[x][y]) int *m2:y行z列的矩阵(array2[y][z]) int x:矩阵m1的行数 int y:矩阵m1的列数/矩阵m2的行数 int z:矩阵m2的列数输出参数: int *r:矩阵m1, m2相乘的结果(array3[x][z])返回值: void
输入描述
输入说明:1、第一个矩阵的行数2、第一个矩阵的列数和第二个矩阵的行数3、第二个矩阵的列数4、第一个矩阵的值5、第二个矩阵的值
输出描述
输出两个矩阵相乘的结果
输入例子
2223 88 09 018 9
输出例子
171 7272 0
算法实现
import java.util.Scanner;/** * Declaration: All Rights Reserved !!! */public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { int x = scanner.nextInt(); int y = scanner.nextInt(); int z = scanner.nextInt(); int[][] a = new int[x][y]; int[][] b = new int[y][z]; for(int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { a[i][j] = scanner.nextInt(); } } for(int i = 0; i < y; i++) { for (int j = 0; j < z; j++) { b[i][j] = scanner.nextInt(); } } System.out.println(matrixMultiply(a, b)); } scanner.close(); } private static String matrixMultiply(int[][] a, int[][] b) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < a.length; i++) { for (int j = 0; j < b[0].length; j++) { int result = 0; for (int k = 0; k < a[0].length; k++) { result += a[i][k] * b[k][j]; } builder.append(result).append(' '); } builder.setCharAt(builder.length() - 1, '\n'); } return builder.substring(0, builder.length() - 1); }}