Java 程序:两个矩阵相减

编写一个Java程序,通过示例减去两个矩阵,或对两个多维数组执行减法运算。

在这个两个矩阵相减的程序中,我们声明了两个矩阵。接下来,我们使用For Loop遍历这些值。在该循环中,我们对x和y矩阵执行乘法运算,并将其分配给另一个名为multi的矩阵。之后,我们使用另一个for循环打印最终输出。

public class SubtractTwoMatrix {

	public static void main(String[] args) {
		int[][] x = {{10, 12, 3}, {44, 25, 9}, {22, 8, 9}};
		int[][] y = {{ 5, 6, 7}, {8, 9,10}, {2, 35, 4}};
		
		int[][] sub = new int[3][3];
		int i, j;
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				sub[i][j] = x[i][j] - y[i][j];
			}
		}
		System.out.println("------ The Subtraction Matrix Y from Matrix X -----");
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				System.out.format("%d \t", sub[I][j]);
			}
			System.out.println("");
		}
	}
}
Java program to Subtract two Matrices

Java 程序:两个矩阵相减示例

这个 Java 程序与上面相同。但是,此代码允许用户输入矩阵的行、列和项。请参阅 for loop

import java.util.Scanner;

public class Example {
	private static Scanner sc;
	public static void main(String[] args) {
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Enter the Rows & Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] arr1 = new int[rows][columns];
		int[][] arr2 = new int[rows][columns];
		
		System.out.println("\n Enter the First Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr1[i][j] = sc.nextInt();
			}		
		}
		System.out.println("\n Enter the Second Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				arr2[i][j] = sc.nextInt();
			}		
		}
		System.out.println("------ The Subtraction Matrix arr2 from arr1 -----");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				System.out.format("%d \t", (arr1[i][j] - arr2[i][j]));
			}
			System.out.println("");
		}
	}
}
 Enter the Rows & Columns :  
3 3

 Enter the First Items :  
10 20 30
40 50 60
70 80 90

 Enter the Second Items :  
5 35 65
9 22 95
90 65 200
------ The Subtraction Matrix arr2 from arr1 -----
5 	-15 	-35 	
31 	28 	-35 	
-20 	15 	-110