java输入两个矩阵计算加减乘法
时间: 2023-05-21 14:00:55 浏览: 119
您好,以下是Java输入两个矩阵计算加减乘法的示例代码:
```
import java.util.Scanner;
public class MatrixOperation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 输入第一个矩阵的行数和列数
System.out.print("请输入第一个矩阵的行数和列数:");
int m1 = input.nextInt();
int n1 = input.nextInt();
// 输入第一个矩阵的元素
System.out.println("请输入第一个矩阵的元素:");
int[][] matrix1 = new int[m1][n1];
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
matrix1[i][j] = input.nextInt();
}
}
// 输入第二个矩阵的行数和列数
System.out.print("请输入第二个矩阵的行数和列数:");
int m2 = input.nextInt();
int n2 = input.nextInt();
// 输入第二个矩阵的元素
System.out.println("请输入第二个矩阵的元素:");
int[][] matrix2 = new int[m2][n2];
for (int i = 0; i < m2; i++) {
for (int j = 0; j < n2; j++) {
matrix2[i][j] = input.nextInt();
}
}
// 计算两个矩阵的加法
if (m1 == m2 && n1 == n2) {
int[][] sum = new int[m1][n1];
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("两个矩阵的加法结果为:");
printMatrix(sum);
} else {
System.out.println("两个矩阵的行数和列数不相等,无法进行加法运算!");
}
// 计算两个矩阵的减法
if (m1 == m2 && n1 == n2) {
int[][] diff = new int[m1][n1];
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
diff[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
System.out.println("两个矩阵的减法结果为:");
printMatrix(diff);
} else {
System.out.println("两个矩阵的行数和列数不相等,无法进行减法运算!");
}
// 计算两个矩阵的乘法
if (n1 == m2) {
int[][] product = new int[m1][n2];
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n2; j++) {
for (int k = 0; k < n1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("两个矩阵的乘法结果为:");
printMatrix(product);
} else {
System.out.println("第一个矩阵的列数不等于第二个矩阵的行数,无法进行乘法运算!");
}
}
// 打印矩阵
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
```
希望能够帮到您!
阅读全文