C++计算正方形矩阵对角线和,对角线分为:主对角线(Principal Diagonal)和 次对角线(secondary diagonal)
输入
4
1 2 3 4
4 3 2 1
7 8 9 6
6 5 4 3
输出
Principal Diagonal Sum: 16
Secondary Diagonal Sum: 20
cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n+5][n+5];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>arr[i][j];
}
}
int sum1=0,sum2=0;
for(int i=0;i<n;i++){
sum1+=arr[i][i];
sum2+=arr[i][n-1-i];
}
cout<<"Principal Diagonal Sum: "<<sum1<<"\n";
cout<<"Secondary Diagonal Sum: "<<sum2;
return 0;
}