C ++中上三角和下三角的总和
在这个问题上,我们得到一个矩阵。我们的任务是创建一个程序来打印上三角和下三角的总和。
下三角
M00 0 0 … 0 M10 M11 0 … 0 M20 M21 M22 … 0 … Mrow0 Mrow1 Mrow2 … Mrow col
上三角
M00 M01 M02 … M0col0 M11 M12 … M1col0 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
热门推荐
10 简短长辈新年祝福语
11 幼教专干调动祝福语简短
12 横幅家庭生日祝福语简短
13 婶婶生日贺词简短祝福语
14 英语简短祝福语给学生
15 女神结婚快乐祝福语简短
16 妈妈给宝贝祝福语简短
17 高考前祝福语简短字句
18 中午生日家庭祝福语简短