程序检查两个给定矩阵在C ++中是否相同
给定两个矩阵M1[r][c]和M2[r][c],行数为“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]=\开始{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]如果对所有矩阵均为true,则打印它们相同,否则打印它们不一样
算法
Start
Step 1 -> define macro as #define n 4
Step 2 -> Declare function to检查矩阵是否相同
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;
//检查矩阵是否相同
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