编写一个Java程序来乘以两个矩阵,并附带示例,或者编写一个程序来执行两个多维数组的乘法。要执行矩阵乘法,第一个矩阵中的列数必须等于第二个矩阵中的总行数。
Java程序,用于乘以两个矩阵
在此示例中,我们声明了两个整数矩阵。接下来,我们使用For Loop来迭代这些值。然后,我们在该循环中对x和y矩阵执行乘法,并将其分配给另一个称为multi的矩阵。之后,我们使用了另一个for循环来打印最终输出。
- Z11 = x11 * y11 = 1 * 5 = 5
- Z12 = x12 * y12 = 2 * 6 = 12
- Z13 = x13 * y13 = 3 * 7 = 21
- Z22 = x22 * y22 = 5 * 9 = 45
public class MultiplyTwoMatrix {
public static void main(String[] args) {
int[][] x = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] y = {{ 5, 6, 7}, {8, 9,10}, {2,3, 4}};
int[][] multi = new int[3][3];
int i, j;
for(i = 0; i < x.length; i++)
{
for(j = 0; j < x[0].length; j++)
{
multi[i][j] = x[i][j] * y[i][j];
}
}
System.out.println("------ The Multiplication of two Matrix ------");
for(i = 0; i < x.length; i++)
{
for(j = 0; j < x[0].length; j++)
{
System.out.format("%d \t", multi[i][j]);
}
System.out.println("");
}
}
}

使用for循环相乘两个矩阵的程序
这个Java程序与上面相同。但是,此代码允许用户输入行、列和矩阵项。
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns;
sc= new Scanner(System.in);
System.out.println("\n Enter Rows & Columns : ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] arr1 = new int[rows][columns];
int[][] arr2 = new int[rows][columns];
System.out.println("\n Enter the First Mat Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
arr1[i][j] = sc.nextInt();
}
}
System.out.println("\n Enter the Second Mat Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
arr2[i][j] = sc.nextInt();
}
}
System.out.println("\n-----The Multiplication of two Matrix----- ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
System.out.format("%d \t", (arr1[i][j] * arr2[i][j]));
}
System.out.println("");
}
}
}
Enter Rows & Columns :
3 3
Enter the First Mat Items :
1 2 3
4 5 6
7 8 9
Enter the Second Mat Items :
10 20 30
40 50 60
70 80 90
-----The Multiplication of two Matrix-----
10 40 90
160 250 360
490 640 810