编写两个矩阵相加的方法:
public static double[][] addMatrix(double[][] a, double[][] b)
编写一个测试程序,提示用户输入两个3 * 3的矩阵,然后显示它们的和。
测试数据:
Enter matrix1: 1 2 3 4 5 6 7 8 9
Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
package com.test.springboot.test;
import java.util.Scanner;
public class TwoMatrixSum {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)) {
// 输入矩阵1
System.out.print("Enter the row and column of matrix 1: ");
double[][] a = new double[input.nextInt()][input.nextInt()]; // 矩阵1
System.out.println("Enter matrix1: ");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++)
a[i][j] = input.nextDouble();
}
// 输入矩阵2
System.out.print("Enter the row and column of matrix 2: ");
double[][] b = new double[input.nextInt()][input.nextInt()]; // 矩阵2
System.out.println("Enter matrix2: ");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++)
b[i][j] = input.nextDouble();
}
// 打印矩阵计算结果
printMatrix(a, b, addMatrix(a, b), '+');
}
}
/** 计算两个矩阵相加 */
public static double[][] addMatrix(double[][] a, double[][] b) {
// 如果矩阵行数或列数不相等,抛出异常
if (a.length != b.length || a[0].length != b[0].length)
throw new IllegalArgumentException("Invalid matrix");
double[][] sum = new double[a.length][a[0].length]; // 矩阵之和
for (int i = 0; i < sum.length; i++)
for (int j = 0; j < sum[i].length; j++)
sum[i][j] = a[i][j] + b[i][j];
return sum;
}
/**打印矩阵*/
public static void printMatrix(double[][] a, double[][] b, double[][] c, char op) {
for (int i = 0; i < c.length; i++) { // 控制行数
for (int j = 0; j < c[i].length; j++) // 打印矩阵1
System.out.printf("%5.1f", a[i][j]);
// 打印矩阵间的操作符或空格
System.out.print((i == c.length / 2) ? " " + op + " " : " ");
for (int j = 0; j < c[i].length; j++) // 打印矩阵2
System.out.printf("%5.1f", b[i][j]);
// 打印矩阵间的操作符或空格
System.out.print((i == c.length / 2) ? " = " : " ");
for (int j = 0; j < c[i].length; j++) // 打印矩阵之和
System.out.printf("%5.1f", c[i][j]);
System.out.println(); // 打印换行符
}
}
}