输入一个nxn矩阵各元素的值,球出两条对角线元素之和

运行代码:

 1 #include<iostream>
 2 using namespace std;
 3 void main()
 4 {    
 5     int n,i,j,sum1=0,sum2=0,a[100][100];
 6     cout<<"请输入矩阵的长度n:";cin>>n;
 7     for(i=0;i<n;i++)
 8         for(j=0;j<n;j++)
 9             cin>>a[i][j];
10     for(i=0;i<n;i++)
11         for(j=0;j<n;j++)
12         {
13             if(i==j) sum1+=a[i][j];
14             if(i+j==n-1) sum2+=a[i][j];
15         }
16         cout<<"对角线1元素之和"<<sum1<<endl;
17         cout<<"对角线2元素之和"<<sum2<<endl;
18 }

运行截图:

posted @ 2012-06-28 19:51  iamvirus  阅读(3455)  评论(0编辑  收藏  举报