简体   繁体   English

使用for循环在C ++中打印矩阵辅助对角线?

[英]Print matrix secondary diagonal in C++ with for loop?

I have a simple program in which I want to print all of the elements in the secondary diagonal of the matrix - these are the numbers 5,9,13,-21,12 but the program does not work as expected. 我有一个简单的程序,我要在其中打印矩阵次对角线上的所有元素-这些是数字5,9,13,-21,12,但该程序无法正常工作。 What am I doing wrong? 我究竟做错了什么?

#include <iostream>
#define SIZE 5
int a[SIZE][SIZE]={
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{100,-21,-70,345,77},
{12,17,765,98,55}
};

for(int i=0;i<5;i++)//The first index increases
for(int k=5;k>0;k--)//The second index decreases
cout<<a[i][k]<<endl;//Printing the element

There is no need for a second for loop . 不需要第二个for循环 You can do it using only one: 您只能使用以下方法之一:

for (int i = 0; i < SIZE; i++){
    std::cout << a[i][SIZE - i - 1] << ' ';
}

This way you have two indexes going opposite ways using a single for loop. 这样,您可以使用一个for循环使两个索引相反。

Well, you did 好吧,你做到了

for (k=5; k>0; k--)

but there is no a[0][5] 但没有a[0][5]

the last element in the first row is a[0][4] so your array should start from 4 and go down to 0 第一行中的最后一个元素是a[0][4]因此您的数组应从4开始并下降到0

for (k=4; k>=0; k--)

Btw it can be done with just 1 loop. 顺便说一句,只需1个循环即可完成。

For every element of the second diagonal, the sum of the indexes is 4. 对于第二个对角线的每个元素,索引的总和为4。

0+4=4
1+3=4
2+2=3
3+1=4
4+0=4

so you can write it as a[i][4-i] 因此您可以将其写为a[i][4-i]

for(i=0; i<5; i++) 
cout<<a[i][4-i]<<endl;

Try doing in this way: 尝试以这种方式做:

for(int i=0; i<5; i++) {
    cout << a[i][4-i] << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM