矩阵相加

矩阵相加


package cn.yamon.array;

import java.util.Arrays;

/**
 * 矩阵的相加
 */
public class MutilpArrays {
    public static void main(String[] args) {
        /*二维矩阵
         *  1 2 3 4
         *  5 6 7 8
         *  9 10 11 12
         *  13 14 15 16
         * */
        int[][] as = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16}
        };
        int [][] bs={
                {2,2,2,2},
                {3,3,3,3},
                {4,4,4,4},
                {5,5,5,5}
        };
        //判断是否可以相加
        if(as.length!=bs.length){
            System.out.println("矩阵的行数不一样,无法相加");
        }else{
            for (int i = 0; i < as.length; i++) {
                for (int j = 0; j < as[i].length; j++) {
                    bs[i][j]=as[i][j]+bs[i][j];
                }
            }
            //System.out.println(Arrays.deepToString(bs));
            for (int[] arr :
                    bs) {
                for (int n :
                        arr) {
                    System.out.print(n+",");
                }
                System.out.println();
            }
        }


    }
}
博客网站 https://yamon.top 个人网站 https://yamon.top/resume GitHub网站 https://github.com/yamonc 欢迎前来访问
原文地址:https://www.cnblogs.com/chenyameng/p/11429662.html