在 C++ 程序中查找由同一矩阵的行主序和列主序相加形成的矩阵的迹

c++server side programmingprogramming

在本教程中,我们将编写一个程序来查找由行主序和列主序形成的矩阵的迹。

让我们看看在给定矩阵的顺序时如何形成行主序和列主序矩阵。

顺序 − 3 x 3

行主矩阵

123
456
789

列主矩阵

147
258
369

我们有行主矩阵和列主矩阵。现在,我们必须将这两个矩阵相加。而结果矩阵的迹就是我们想要的结果。

让我们看看如何编写代码来解决这个问题。我们必须完成以下 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

相关文章