我需要在C++中计算矩阵的两条对角线之和,尽管我已经有了一个解决方案,但我很蠢因为我无法理解它在做什么,所以我想知道是否有另一个版本的解决方案,我可以理解。以下是执行此任务的代码:
cout<<"Jepi rangun e matrices"<<endl; // pra bejme manipulim me matrice katrore ku rreshtat=kolonat
cin>>n;
cout<<"Tani jepi elementet e matrices"<<endl; // lexohet matrica
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cin>>a[i][j];
}
d=0;
s=0; // ketu e keni kushtin si dhe mbledhjen per te dy diagonalet me dy variabla te ndryshme
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i==j)
d=d+a[i][j];
if(j==n-i+1 || i==n-j+1)
s=s+a[i][j];
}
难以理解的部分是:
if(j==n-i+1 || i==n-j+1)
s=s+a[i][j];
这是我改变了整个代码,但它不能处理次对角线:
#include <iostream>
using namespace std;
int main()
{
int d=0,s=0; // ketu e keni kushtin si dhe mbledhjen per te dy diagonalet me dy variabla te ndryshme
int i,j,n;
int a[5][5];
cout<<"Jepi rangun e matrices"<<endl; // pra bejme manipulim me matrice katrore ku rreshtat=kolonat
cin>>n;
cout<<"Tani jepi elementet e matrices"<<endl; // lexohet matrica
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cin>>a[i][j];
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
d+=a[i][j]; //principal diagonal
if(i+j==n-1)
s+=a[i][j];//secondary diagonal
}
}
cout << d << endl;
cout << s << endl;
cin.get();
cin.get();
return 0;
}