在 C++ 程序中查找由相同矩阵的行主序和列主序相加形成的矩阵的迹
在本教程中,我们将编写一个程序,查找由行主序和列主序矩阵形成的矩阵的迹。
让我们看看如何在给定矩阵的阶数时形成行主序和列主序矩阵。
阶数 − 3 x 3
行主序矩阵 −
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
列主序矩阵 −
| 1 | 4 | 7 |
| 2 | 5 | 8 |
| 3 | 6 | 9 |
我们有行主序和列主序矩阵。现在,我们必须将这两个矩阵相加。结果矩阵的迹是我们正在寻找的结果。
让我们看看如何编写代码来解决问题。我们必须完成以下 4 个步骤才能完成问题的解决方案。
创建行主序矩阵。
创建列主序矩阵。
将两个矩阵相加并存储结果矩阵。
查找结果矩阵的迹并打印结果。
示例
让我们看看代码。
#include <iostream>
#include <bits/stdc++.h>
#include <regex>
using namespace std;
int traceOfRowAndColumnMajorMatrices(int m, int n) {
int row_major[m][n], column_major[m][n], addition_result[m][n], count = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
row_major[i][j] = count;
count += 1;
}
}
count = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
column_major[j][i] = count;
count += 1;
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
addition_result[j][i] = row_major[i][j] + column_major[i][j];
}
}
int trace = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
trace += addition_result[i][j];
}
}
}
return trace;
}
int main() {
int m = 3, n = 3;
cout << traceOfRowAndColumnMajorMatrices(m, n) << endl;
return 0;
}输出
如果执行上述程序,则将获得以下结果。
30
结论
如果您在本教程中有任何疑问,请在评论区中提出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP