在 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
結論
如果您在本教程中有任何疑問,請在評論區中提出。
廣告