Java两个矩阵相加生成c矩阵,对c矩阵元素查询,输出行和列
时间: 2023-09-27 09:08:39 浏览: 83
好的,下面是Java代码实现:
```java
import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 输入第一个矩阵的行数和列数
System.out.print("Enter the number of rows and columns of the first matrix: ");
int m1 = input.nextInt();
int n1 = input.nextInt();
// 创建第一个矩阵
int[][] matrix1 = new int[m1][n1];
System.out.println("Enter the first matrix:");
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
matrix1[i][j] = input.nextInt();
}
}
// 输入第二个矩阵的行数和列数
System.out.print("Enter the number of rows and columns of the second matrix: ");
int m2 = input.nextInt();
int n2 = input.nextInt();
// 创建第二个矩阵
int[][] matrix2 = new int[m2][n2];
System.out.println("Enter the second matrix:");
for (int i = 0; i < m2; i++) {
for (int j = 0; j < n2; j++) {
matrix2[i][j] = input.nextInt();
}
}
// 检查两个矩阵是否可以相加
if (m1 != m2 || n1 != n2) {
System.out.println("The matrices cannot be added.");
} else {
// 创建结果矩阵
int[][] resultMatrix = new int[m1][n1];
// 将两个矩阵相加得到结果矩阵
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// 输出结果矩阵
System.out.println("The result matrix is:");
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
// 查询元素并输出行和列
System.out.print("Enter an element to search for: ");
int element = input.nextInt();
boolean found = false;
for (int i = 0; i < m1; i++) {
for (int j = 0; j < n1; j++) {
if (resultMatrix[i][j] == element) {
System.out.println("The element " + element + " is at (" + i + ", " + j + ")");
found = true;
}
}
}
if (!found) {
System.out.println("The element " + element + " is not in the matrix.");
}
}
input.close();
}
}
```
这段代码实现了两个矩阵的相加,并且可以查询结果矩阵中某个元素所在的行和列。注意,这里假设输入的两个矩阵都是整数矩阵。
阅读全文