C++ 计算矩阵中对角线的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9008505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calculate the sum of diagonals in a matrix
提问by Igor Ivanovski
I need to calculate the sum of two diagonals in a matrix in C++, I already have a solution for that but I must be dumb because I cant understand what it is doing, so I would like to know if there is another version which I can understand. here is the code which does the job:
我需要在 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];
}
The part that is difficult to understand is
难以理解的部分是
if(j==n-i+1 || i==n-j+1)
s=s+a[i][j];
Here is the entire code that I changed but it doesnt work for the secondary diagonal:
这是我更改的整个代码,但它不适用于次对角线:
#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;
}
回答by Vyktor
It would be nice to have comments in English, but, the your code does (second loop):
用英语发表评论会很好,但是,您的代码确实如此(第二个循环):
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
The much nicer and much more effective code (using n
, instead of n^2
) would be:
更好、更有效的代码(使用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)
}
This goes straight trough the diagonals (both at the one loop!) and doesn't go trough other items.
这会直接穿过对角线(都在一个循环中!)并且不会穿过其他项目。
EDIT:
编辑:
Main diagonal has coordinates {(1,1), (2,2), ..., (i,i)}
(therefor i == j
).
主对角线有坐标{(1,1), (2,2), ..., (i,i)}
(因此i == j
)。
Secondary diagonal has coordinates (in matrix 3x3): {(1,3), (2,2),(3,1)}
which in general is: {(1,n-1+1), (2, n-2+1), ... (i, n-i+1), .... (n,1)}
. But in C, arrays are indexed from 0, not 1 so you won't need that +1
(probably).
次对角线具有坐标(在矩阵 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
(可能)。
All those items in secondary diagonal than has to fit condition: i == n - j + 1
(again due to C's indexing from 0 +1
changes to -1
(i=0,
, n=3
, j=2
, j = n - i - 1
)).
次对角线上的所有项目都必须符合条件:(i == n - j + 1
再次由于 C 的索引从 0+1
更改为-1
( i=0,
, n=3
, j=2
, j = n - i - 1
))。
You can achieve all this in one loop (code above).
您可以在一个循环中实现所有这些(上面的代码)。
回答by Ionel Lupu
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
}
}
To understand this algorithm better you should paint a matrix on you notebook and number it's elements with their position in matrix,then apply the algorithm step by step.I'm 100% sure that you will understand
为了更好地理解这个算法,你应该在你的笔记本上画一个矩阵,用它们在矩阵中的位置给它的元素编号,然后一步一步地应用这个算法。我 100% 肯定你会理解
回答by penelope
How about I try to explain this version? :D
我试着解释一下这个版本怎么样?:D
There are 3 important parts of the code:
代码有3个重要部分:
- inputing the matrix
- calculating major diagonal ( \ direction)
- calculating minor diagonal ( / direction)
- 输入矩阵
- 计算主对角线(\方向)
- 计算小对角线( / 方向)
And here they are, explained:
他们在这里,解释说:
// 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
}
Here, d and s contain the inter-values of major and minor diagonal respectively. At the end of 2 loops, they will contain the results
这里,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) ...
}
Hope this helps.
希望这可以帮助。
Note that this code starts matrix coordinates at 1 instead of 0, so you will actually need to allocate (n+1)x(n+1)
space for the matrix:
请注意,此代码从 1 而不是 0 开始矩阵坐标,因此您实际上需要(n+1)x(n+1)
为矩阵分配空间:
double a[n+1][n+1];
before using it.
在使用它之前。
Also, the code you gave is not most effective. It has O(n^2)
complexity, while the task can be done in O(n)
like so:
此外,您提供的代码并不是最有效的。它具有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
}
回答by Abdul Rehman
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";
}
回答by Tnahsoe Tnhsen
you must use i + j == n + 1
instead of i + j == n - 1
for secondary diagonal i.e
您必须使用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
}
}