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

二维数组或矩阵的使用对于几个 应用。矩阵行和列用于保存数字。我们可以定义2D C++中的矩阵也使用多维数组。在本文中,我们将了解如何 使用 C++ 计算给定方阵的对角线和。

矩阵有两个对角线,主对角线和次要对角线(有时 称为大对角线和小对角线)。主要对角线从左上角开始 角(索引 [0, 0])到右下角(索引 [n-1, n-1]),其中 n 是 方阵。主要对角线从右上角(索引 [n-1, 0])到左下角 角(索引 [0, n-1])。让我们看看算法来找到元素的总和以及 这两个对角线。

矩阵对角线和

⎡⎣⎢862574319 ⎤⎦⎥,[853671249 ],

<span style="color:#000000">Sum of all elements in major diagonal: (8 + 7 + 9) = 24
Sum of all elements in minor diagonal: (3 + 7 + 2) = 12
</span>

在前面的示例中,使用了一个 3 x 3 矩阵。我们已经扫描了对角线 单独并计算总和。让我们看看算法和实现清晰 视图。

算法

  • 读取矩阵 M 作为输入
  • 考虑 M 有 n 行和 n 列
  • sum_major := 0
  • sum_minor := 0
  • 对于范围从 0 到 n - 1 的 i,请执行
    • 对于从 0 到 n - 1 的 j 朗吉格,执行
      • 如果 i 和 j 相同,则
        • sum_major := sum_major + M[ i ][ j ]
      • 结束如果
      • 如果 (i + j) 与 (N - 1) 相同,则
        • sum_minor := sum_minor + M[ i ][ j ]
      • 结束如果
    • 结束
  • 结束
  • 返回总和



#include <iostream> #include <cmath> #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 << "The sum of major diagonal: " << sum_major << endl ; cout << "The sum of minor diagonal: " << sum_minor << endl ; } int main ( ) { int mat1 [ N ] [ N ] = { { 5 , 8 , 74 , 21 , 69 , 78 , 25 } , { 48 , 2 , 98 , 6 , 63 , 52 , 3 } , { 85 , 12 , 10 , 6 , 9 , 47 , 21 } , { 6 , 12 , 18 , 32 , 5 , 10 , 32 } , { 8 , 45 , 74 , 69 , 1 , 14 , 56 } , { 7 , 69 , 17 , 25 , 89 , 23 , 47 } , { 98 , 23 , 15 , 20 , 63 , 21 , 56 } , } ; cout << "For the first matrix: " << endl ; solve ( mat1 ) ; int mat2 [ N ] [ N ] = { { 6 , 8 , 35 , 21 , 87 , 8 , 26 } , { 99 , 2 , 36 , 326 , 25 , 24 , 56 } , { 15 , 215 , 3 , 157 , 8 , 41 , 23 } , { 96 , 115 , 17 , 5 , 3 , 10 , 18 } , { 56 , 4 , 78 , 5 , 10 , 22 , 58 } , { 85 , 41 , 29 , 65 , 47 , 36 , 78 } , { 12 , 23 , 87 , 45 , 69 , 96 , 12 } } ; cout << "\nFor the second matrix: " << endl ; solve ( mat2 ) ; }

输出

<span style="color:#000000">For the first matrix: 
The sum of major diagonal: 129
The sum of minor diagonal: 359

For the second matrix: 
The sum of major diagonal: 74
The sum of minor diagonal: 194
</span>

结论

在本文中,我们已经看到了如何计算给定方阵的对角线和。 大对角线从左上角开始到右下角,小对角线从小角开始 对角线从右上角开始到左下角。要找到这些的总和 对角线元素,我们遍历所有元素。当行和列索引值都可用时 相同,表示主要对角线元素,当两个指数之和为 与 n – 1 相同,其中 n 是矩阵的顺序,它将添加到次要对角线。这 过程需要两个嵌套循环,我们正在遍历 2D 阵列。所以它将需要 O(n2) amount of time to compute the sum of two diagonals of the given matrix.

posted @ 2022-12-17 20:42  很酷的站长  阅读(472)  评论(0编辑  收藏  举报
70博客 AI工具 源码下载