The utilization of 2-dimensional arrays or matrices is extremely advantageous for several
applications. Matrix rows and columns are used to hold numbers. We can define 2D
在C++中使用多维数组来表示矩阵。在本文中,我们将看看如何实现
use C++ to calculate the diagonal sum of a given square matrix.
The matrices have two diagonals, the main diagonal and the secondary diagonal (sometimes
referred to as major and minor diagonals). The major diagonal starts from the top-left
corner (index [0, 0]) to the bottom-right corner (index [n-1, n-1]) where n is the order of the
正方形矩阵。主对角线从右上角(索引[n-1, 0])开始,到左下角
corner (index [0, n-1]). Let us see the algorithm to find the sum of the elements along with
these two diagonals.
Matrix Diagonal Sum
的中文翻译为:
矩阵对角线之和
$$begin{bmatrix}
8 & 5& 3newline
6 & 7& 1newline
2 & 4& 9
end{bmatrix},$$
Sum of all elements in major diagonal: (8 + 7 + 9) = 24
Sum of all elements in minor diagonal: (3 + 7 + 2) = 12
登录后复制
In the previous example, one 3 x 3 matrix was used. We have scanned the diagonals
individually and calculated the sum. Let us see the algorithm and implementation for a clear
view.
Algorithm
- 读取矩阵 M 作为输入
- 考虑 M 具有 n 行和 n 列
- sum_major := 0
- sum_minor := 0
- 对于i从0到n-1的范围,执行
- for j rangign from 0 to n - 1, do
- if i and j are the same, then
- sum_major := sum_major + M[ i ][ j ]
- end if
- if (i + j) is same as (N - 1), then
- sum_minor := sum_minor + M[ i ][ j ]
- end if
- if i and j are the same, then
- end for
- end for
- return sum
Example
#include
#include
#define N 7
using namespace std;
float solve( int M[ N ][ N ] ){
int sum_major = 0;
int sum_minor = 0;
for ( int i = 0; i < N; i++ ) {
for ( int j = 0; j < N; j++ ) {
if( i == j ) {
sum_major = sum_major + M[ i ][ j ];
}
if( (i + j) == N - 1) {
sum_minor = sum_minor + M[ i ][ j ];
}
}
}
cout