输入两个m行n列的矩阵对象,输出两个矩阵的和以及第一个矩阵的转置矩阵java
时间: 2024-06-18 19:05:11 浏览: 190
可以通过以下Java代码实现输入两个m行n列的矩阵对象,输出两个矩阵的和以及第一个矩阵的转置矩阵:
```
import java.util.Scanner;
public class MatrixAdditionAndTranspose {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m, n, i, j;
// 输入第一个矩阵
System.out.print("Enter the number of rows and columns of the first matrix: ");
m = input.nextInt();
n = input.nextInt();
int[][] matrix1 = new int[m][n];
System.out.println("Enter the first matrix: ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
matrix1[i][j] = input.nextInt();
}
}
// 输入第二个矩阵
System.out.print("Enter the number of rows and columns of the second matrix: ");
m = input.nextInt();
n = input.nextInt();
int[][] matrix2 = new int[m][n];
System.out.println("Enter the second matrix: ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
matrix2[i][j] = input.nextInt();
}
}
// 输出两个矩阵的和
System.out.println("The sum of the matrices is: ");
for (i = 0; i < matrix1.length; i++) {
for (j = 0; j < matrix1[i].length; j++) {
System.out.print(matrix1[i][j] + matrix2[i][j] + " ");
}
System.out.println();
}
// 输出第一个矩阵的转置矩阵
System.out.println("The transpose of the first matrix is: ");
for (i = 0; i < matrix1.length; i++) {
for (j = 0; j < matrix1.length; j++) {
System.out.print(matrix1[j][i] + " ");
}
System.out.println();
}
}
}
```
阅读全文