集册 Java实例教程 编写两个矩阵加和减的代码

编写两个矩阵加和减的代码

欢马劈雪     最近更新时间:2020-01-02 10:19:05

666
编写两个矩阵加和减的代码

import java.util.Random;


public class Main {//from N  o w  J a v a . c o m


   public static void main(String[] args) {

       int rows = 5;

       int columns = 5;

       int[][] a = readMatrix(rows, columns);

       int[][] b = readMatrix(rows, columns);

       int[][] sum = add(a, b);

       int[][] difference1 = subtract(a, b);

       int[][] difference2 = subtract(b, a);

       System.out.println();

       System.out.println("A + B =");

       printMatrix(sum);

       System.out.println();

       System.out.println("A - B =");

       printMatrix(difference1);

       System.out.println();
       /** from 
       时代Java公众号 - nowjava.com**/

       System.out.println("B - A =");

       printMatrix(difference2);

   }


   public static int[][] readMatrix(int rows, int columns) {

       int[][] result = new int[rows][columns];

       for (int i = 0; i < rows; i++) {

           for (int j = 0; j < columns; j++) {

               result[i][j] = new Random().nextInt();

           }

       }

       return result;

   }


   public static int[][] add(int[][] a, int[][] b) {

       //your code here

   }


   public static int[][] subtract(int[][] a, int[][] b) {

       //your code here

   }


   public static void printMatrix(int[][] matrix) {

       
展开阅读全文