C++ 中的上三角形和下三角形的總和


在此問題中,我們給定了一個矩陣。我們的任務是建立一個程式來列印上三角形和下三角形的和。

下三角形

M00                     0             0       …        0
M10                     M11               0       …        0
M20                     M21               M22      …        0
…
Mrow0                   Mrow1             Mrow2      … Mrow col

上三角形

M00                     M01               M02          …       M0col
0                 M11               M12          …       M1col
0                 0             M22          …       M2col
…
0                 0             0         …     Mrow col

我們舉個例子來理解這個問題,

Input: {{5, 1, 6}
{8, 2, 0}
{3, 7, 4}}
Output: upper triangle sum = 18
lower triangle sum = 29
Explanation:
Sum of upper triangle sum = 5 + 1 + 6 + 2 + 0 + 4 = 18
Sum of lower triangle sum = 5 + 8 + 2 + 3 + 7 + 4 = 29

針對此問題的一個簡單解決方案。我們將使用迴圈遍歷上三角形元素和下三角形元素中的陣列。用兩個單獨的變數 lSum 和 uSum 計算求和。

示例

演示我們解決方案的工作原理的程式,

 線上演示

#include <iostream>
using namespace std;
int row = 3;
int col = 3;
void sum(int mat[3][3]) {
   int i, j;
   int uSum = 0;
   int lSum = 0;
   for (i = 0; i < row; i++)
      for (j = 0; j < col; j++) {
         if (i <= j) {
         uSum += mat[i][j];
      }
   }
   cout<<"Sum of the upper triangle is "<<uSum<<endl;
   for (i = 0; i < row; i++)
      for (j = 0; j < col; j++) {
         if (j <= i) {
            lSum += mat[i][j];
      }
   }
   cout<<"Sum of the lower triangle is "<<lSum<<endl;
}
int main() {
   int mat[3][3] = { { 5, 1, 6 },
                  { 8, 2, 0 },
                     { 3, 7, 4 }};
   sum(mat);
   return 0;
}

輸出

Sum of the upper triangle is 18
Sum of the lower triangle is 29


更新日期:2020 年 8 月 17 日

988 檢視

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.