C++ 中檢查兩個給定的矩陣是否相等的程式


給定兩個具有 ‘r’ 行和 ‘c’ 列的矩陣 M1[r][c] 和 M2[r][c],我們必須檢查這兩個給定的矩陣是否相同。如果它們相同,則列印“矩陣相同”,否則列印“矩陣不同”

相同矩陣

當滿足以下條件時,兩個矩陣 M1 和 M2 被稱為相同−

  • 這兩個矩陣的行數和列數相同。
  • M1[i][j] 的值等於 M2[i][j]。

如下面的給定圖中所示,兩個 3x3 的矩陣 m1 和 m2 是相同的 −

$$M1[3][3]=\begin{bmatrix}1 & 2 & 3 \ 4 & 5 & 6 \ 7 & 8 & 9 \ \end {bmatrix} \:\:\:\:M2[3][3] =\begin{bmatrix}1 & 2 & 3 \ 4 & 5 & 6 \ 7 & 8 & 9 \ \end{bmatrix} $$

示例

Input: a[n][n] = { {2, 2, 2, 2},
   {2, 2, 2, 2},
   {3,3, 3, 3},
   {3,3, 3, 3}};
   b[n][n]= { {2, 2, 2, 2},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {3, 3, 3, 3}};
Output: matrices are identical
Input: a[n][n] = { {2, 2, 2, 2},
   {2, 2, 1, 2},
   {3,3, 3, 3},
   {3,3, 3, 3}};
   b[n][n]= { {2, 2, 2, 2},
      {2, 2, 5, 2},
      {3, 3, 3, 3},
      {3, 3, 3, 3}};
Output: matrices are not identical

方法

遍歷這兩個矩陣 a[i][j] 和 b[i][j],並檢查 a[i][j]==b[i][j],如果對所有條件都成立,則列印它們是相同的,否則列印它們是不同的。 

演算法

Start
Step 1 -> define macro as #define n 4
Step 2 -> Declare function to check matrix is same or not
   int check(int a[][n], int b[][n])
      declare int i, j
      Loop For i = 0 and i < n and i++
         Loop For j = 0 and j < n and j++
            IF (a[i][j] != b[i][j])
               return 0
            End
      End
   End
   return 1
Step 3 -> In main()
   Declare variable asint a[n][n] = { {2, 2, 2, 2},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {3, 3, 3, 3}}
   Declare another variable as int b[n][n] = { {2, 2, 2, 2},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {3, 3, 3, 3}}
   IF (check(a, b))
      Print matrices are identical
   Else
      Print matrices are not identical
Stop

示例

#include <bits/stdc++.h>
#define n 4
using namespace std;
// check matrix is same or not
int check(int a[][n], int b[][n]){
   int i, j;
   for (i = 0; i < n; i++)
      for (j = 0; j < n; j++)
         if (a[i][j] != b[i][j])
      return 0;
   return 1;
}
int main(){
   int a[n][n] = { {2, 2, 2, 2},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {3, 3, 3, 3}};
   int b[n][n] = { {2, 2, 2, 2},
      {2, 2, 2, 2},
      {3, 3, 3, 3},
      {3, 3, 3, 3}};
   if (check(a, b))
      cout << "matrices are identical";
   else
      cout << "matrices are not identical";
   return 0;
}

輸出

matrices are identical

更新時間:23-Sep-2019

910 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

入門
廣告
© . All rights reserved.