import java.util.Scanner;编写程序,完成二维数组相乘任务
时间: 2024-06-04 09:13:52 浏览: 8
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 in matrix 1: ");
int rows1 = input.nextInt();
System.out.print("Enter the number of columns in matrix 1: ");
int cols1 = input.nextInt();
int[][] matrix1 = new int[rows1][cols1];
System.out.println("Enter the elements of matrix 1: ");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = input.nextInt();
}
}
System.out.print("Enter the number of rows in matrix 2: ");
int rows2 = input.nextInt();
System.out.print("Enter the number of columns in matrix 2: ");
int cols2 = input.nextInt();
int[][] matrix2 = new int[rows2][cols2];
System.out.println("Enter the elements of matrix 2: ");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = input.nextInt();
}
}
if (cols1 != rows2) {
System.out.println("Matrices cannot be multiplied");
return;
}
int[][] product = new int[rows1][cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
product[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 < cols2; j++) {
System.out.print(product[i][j] + " ");
}
System.out.println();
}
}
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)