📅  最后修改于: 2023-12-03 14:53:46.646000             🧑  作者: Mango
本程序是一个Java程序,可以让你将两个任意大小的矩阵相乘。
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows for matrix1: ");
int rows1 = input.nextInt();
System.out.print("Enter the number of columns for matrix1: ");
int columns1 = input.nextInt();
int[][] matrix1 = new int[rows1][columns1];
System.out.println("Enter the elements of matrix1:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns1; j++) {
matrix1[i][j] = input.nextInt();
}
}
System.out.print("Enter the number of rows for matrix2: ");
int rows2 = input.nextInt();
System.out.print("Enter the number of columns for matrix2: ");
int columns2 = input.nextInt();
int[][] matrix2 = new int[rows2][columns2];
System.out.println("Enter the elements of matrix2:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < columns2; j++) {
matrix2[i][j] = input.nextInt();
}
}
if (columns1 != rows2) {
System.out.println("The two matrices cannot be multiplied.");
System.exit(0);
}
int[][] resultMatrix = new int[rows1][columns2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
for (int k = 0; k < columns1; k++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("The product of the matrices is:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}
上面的代码实现了向用户请求输入两个矩阵的行和列,以及矩阵中每个元素的值。接下来,它检查这两个矩阵是否可以相乘,并计算出它们的乘积。最后,程序输出结果矩阵的值。
要运行该程序,请按照以下步骤操作:
javac MatrixMultiplication.java
。java MatrixMultiplication
。本程序实现了矩阵乘法的功能,可以让用户输入两个矩阵的行和列,然后计算它们的乘积。通过本程序,用户可以学习如何在Java中使用多维数组、循环和条件语句。