Java程序两个矩阵相加

时间:2020-02-23 14:35:06  来源:igfitidea点击:

在本教程中,我们将看到如何在java中将两个矩阵进行相加。
我们可以将其扩展为n * n矩阵。

import java.util.Scanner;
 
public class MatrixOperator
{
   public static void main(String args[])
   {
       int i, j;
       int mat1[][] = new int[3][3];
       int mat2[][] = new int[3][3];
       int res[][] = new int[3][3];
       Scanner scanner = new Scanner(System.in);
	   
       System.out.print("Enter matrix 1 elements : ");
       for(i=0; i<3; i++){
           for(j=0; j<3; j++){
               mat1[i][j] = scanner.nextInt();
           }
       }
	   
       System.out.print("Enter matrix 2 elements : ");
       for(i=0; i<3; i++){
           for(j=0; j<3; j++){
               mat2[i][j] = scanner.nextInt();
           }
       }
	   
       for(i=0; i<3; i++){
           for(j=0; j<3; j++){
               res[i][j] = mat1[i][j] + mat2[i][j];
           }
       }
	   
       System.out.print("The new matrix is :\n");
       for(i=0; i<3; i++){
           for(j=0; j<3; j++){
               System.out.print(res[i][j]+ " ");
           }
           System.out.println();
       }
   }
}

输出:

Enter matrix 1 elements : 11 22 33 44 55 66 77 88 99
Enter matrix 2 elements : 10 20 30 40 50 60 70 80 90
The new matrix is :
21 42 63
84 105 126
147 168 189