Java、两个矩阵相加

编写两个矩阵相加的方法:
        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();   // 打印换行符
        }
    }

}

 

 

 

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值