Java程式檢查兩個給定矩陣是否相同
問題陳述
如果兩個矩陣的行數和列數相等,並且對應的元素也相等,則這兩個矩陣相同。如下所示:
輸入
Matrix A = 1 2 3 4 5 6 7 8 9 Matrix B = 1 2 3 4 5 6 7 8 9 The matrices A and B are identical
輸出
Both the matrices are identical
檢查兩個給定矩陣是否相同的步驟
以下是檢查兩個給定矩陣是否相同的步驟:
- 透過定義兩個**二維陣列**來初始化兩個矩陣,以表示這些矩陣。
- 使用一個變數(例如,flag)設定一個標誌來跟蹤矩陣是否相同。最初,將其設定為1(true)。
- 使用巢狀迴圈遍歷兩個矩陣的每個元素,比較對應的元素。
- 如果兩個矩陣中任意一對元素不同,則將標誌設定為**0**(false)。
- 迴圈結束後,如果標誌仍然為**1**,則列印矩陣相同。否則,列印它們不同。
Java程式檢查兩個給定矩陣是否相同
檢查兩個矩陣是否相同的程式如下所示:
public class Example {
public static void main (String[] args) {
int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
int flag = 1;
int n = 3;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (A[i][j] != B[i][j])
flag = 0;
if (flag == 1)
System.out.print("Both the matrices are identical");
else
System.out.print("Both the matrices are not identical");
}
}
輸出
Both the matrices are identical
程式碼解釋
現在讓我們瞭解上述程式。
定義了兩個矩陣A和B。標誌的初始值為**1**。然後使用巢狀for迴圈比較兩個矩陣的每個元素。如果任何對應的元素不相等,則標誌的值將設定為**0**。演示此功能的程式碼片段如下所示:
int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };
int flag = 1;
int n = 3;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (A[i][j] != B[i][j])
flag = 0;
如果標誌為1,則矩陣相同,並顯示出來。否則,矩陣不同,並顯示出來。演示此功能的程式碼片段如下所示:
if (flag == 1)
System.out.print("Both the matrices are identical");
else
System.out.print("Both the matrices are not identical");/pre>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP