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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP