计算矩阵中对角线的和

calculate the sum of diagonals in a matrix

本文关键字:对角线 计算      更新时间:2023-10-16

我需要用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;
}

如果有英文注释会很好,但是,您的代码确实如此(第二个循环):

browse all rows
  browse all cells
    if i == j (is in main diagonal):
        increase one sum
    if i == n - i + 1 (the other diagonal)
        increase the second sum

更好、更有效的代码(使用n而不是n^2)是:

for( int i = 0; i < n; i++){
   d += a[i][i];  // main diagonal
   s += a[i][n-i-1]; // second diagonal (you'll maybe need to update index)
}

它直接穿过对角线(都在一个环上!),而不穿过其他项目。

编辑:

主对角线具有坐标{(1,1), (2,2), ..., (i,i)}(因此为i == j)。

次对角线具有坐标(在矩阵3x3中):{(1,3), (2,2),(3,1)},一般为:{(1,n-1+1), (2, n-2+1), ... (i, n-i+1), .... (n,1)}。但在C中,数组是从0索引的,而不是从1索引的,所以您可能不需要+1

次对角线中的所有项目都必须符合条件:i == n - j + 1(再次由于C的索引从0 +1变为-1i=0,n=3j=2j = n - i - 1))。

您可以在一个循环中实现所有这些(上面的代码)。

int diag1=0;
int diag2=0;
for (i=0;i<n;i++)
 for (j=0;j<n;j++){
  if(i==j)  diag1+=a[i][j]; //principal diagonal 
  if(i+j==n-1) diag2+=a[i][j];//secondary diagonal

}

为了更好地理解这个算法,你应该在笔记本上画一个矩阵,用矩阵中元素的位置对其进行编号,然后逐步应用算法。我百分之百相信你会理解

我试着解释一下这个版本怎么样?:D

代码有三个重要部分:

  • 输入矩阵
  • 计算主对角线(\方向)
  • 计算小对角线(/方向)

他们在这里,解释道:

// input elements
for(i=1;i<=n;i++) // from left to right
{
    for(j=1;j<=n;j++) // from up to down
        cin>>a[i][j]; // input element at (i,j) position
}

这里,d和s分别包含主对角线和次对角线的插值。在2个循环结束时,它们将包含结果

for (i=1;i<=n;i++)
     for (j=1;j<=n;j++)
     {
        if(i==j)          // major diagonal - if coordinates are the same
           d=d+a[i][j];   // e.g. (1,1), (2,2)
        if(j==n-i+1 || i==n-j+1)  // coordinates of the minor diagonal - check
           s=s+a[i][j];           // e.g. n=3 (3,1) (2,2) ...
      }

希望这能有所帮助。

请注意,此代码以1而不是0开始矩阵坐标,因此您实际上需要为矩阵分配(n+1)x(n+1)空间:

double a[n+1][n+1];

此外,你给出的代码也不是最有效的。它具有O(n^2)的复杂性,而任务可以在O(n)中完成,如下所示:

// matrix coordinates now start from 0
for (int i=0; i < n; ++i){
    d += a[i][i]; // major
    s += a[i][n-1-i]; // minor
}
int num[5][5]={0}; //decleration
int i=0,j=0,sum=0; 
for (int i=0;i<5;i++)
{
    for (int j=0;j<5;j++)
    {
        cin>>num[i][j];
    }                          //Taking Matrix input
}
        cout<<endl<<"The Matrix is "<<endl;
    for (int i=0;i<5;i++)
    {
        for (int j=0;j<5;j++)
        {
            cout<<num[i][j]<<" ";
        }
            cout<<endl;               //Displaying the Matrix
    }                               
cout<<endl<<"The sum of diagonals of the matrix is "<<endl;
if(i==j) 
{
    for (i=0;i<5;i++)
    {
        for (j=0;j<5;j++)
        {
            if (i==j)       //This loop works where i and j will be equal
            {
            sum=sum+num[i][j];
            }
        }
    }
    cout<<sum;
}
else   //Some times the user creates 4 x 3 matrix or so than diagonals not match so. . . 
{
    cout<<"The sum is not Possible";
}

对于辅助对角线,即,必须使用i + j == n + 1而不是i + j == n - 1

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
    }
}