【c++】输入一个n×n的矩阵,求出两条对角线元素值之和,输出矩阵,求最大值、最小值及下标
#include<iostream> using namespace std; int main(){ int n; int a[100][100],i,j; cout<<"请输入n*n矩阵的n值:"; cin>>n; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<"a["<<i<<"]["<<j<<"]="; cin>>a[i][j]; } cout<<endl; } //输出矩阵 cout<<"生成的矩阵为:\n"; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<a[i][j]<<'\t'; } cout<<endl; } //求矩阵对角线和 cout<<"矩阵对角线和为:"; int sum=0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(i==j){ cout<<a[i][j]; if (i<n-1) cout<<"+"; else cout<<"="; sum+=a[i][j]; } } } cout<<sum<<endl; //求矩阵最大值、最小值及下标 int max,min,a1,a2,b1,b2; max=min=a[0][0]; a1=a2=b1=b2=0; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if (max<a[i][j]) {max=a[i][j];a1=i;b1=j;} if (min>a[i][j]) {min=a[i][j];a2=i;b2=j;} } } cout<<"矩阵最大值a["<<a1+1<<"]["<<b1+1<<"]="<<max<<endl; cout<<"矩阵最小值a["<<a2<<"]["<<b2<<"]="<<min<<endl; return 0; }
输出结果为: