C++程序计算矩阵对角线之和

C++程序计算矩阵对角线之和

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 登录后复制