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>

更新于:2024年9月20日

1K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.