如何将矩阵 int[,] 的值从左下角到右上角对角相加?
如何将矩阵 int[,] 的值从左下角到右上角对角相加?
我试图帮助朋友理解这一点,但即使我也不太明白他们在这里做什么。
这是我试图向他解释的方法:
public void AddDiagonal()
{
int Addition;
for (int f = 0; f < filas; f++)
{
for (int c = 0; c < columnas; c++)
{
if (f == columnas - c - 1)
{
Addition += matriz[f, c];
}
}
}
}
How could I add the values of a matrix int[,] diagonally from bottomleft, to topright?
I'm trying to help out a friend understand this but even I don't really get what they're doing here.
Here's the method I'm trying to explain to him:
public void AddDiagonal()
{
int Addition;
for (int f = 0; f < filas; f++)
{
for (int c = 0; c < columnas; c++)
{
if (f == columnas - c - 1)
{
Addition += matriz[f, c];
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理解这一点的关键是
if
语句:两个嵌套循环在行上迭代(使用
f
作为索引),并在每行上迭代列(使用c
作为索引)。因此,每次迭代,您都会测试行号(即
f
)是否等于反转的列号(即从总列数 -columnas
)。测试列号反转的原因是因为您想要从左下角到右上角添加,这与从右上角到左下角添加相同。需要注意的一件事是,矩阵对角线仅对方阵有意义,这意味着列数需要与行数相同(在您的算法中
filas
应等于columnas< /代码>)。
因此,假设一个 5x5 矩阵:
第 0 行 (f = 0) -->第 4 列(c = 5 - 0 - 1)
第 1 行 (f = 1) -->第 3 列 (c = 5 - 1 - 1)
第 2 行 (f = 2) -->第 2 列(c = 5 - 2 - 1)
第 3 行 (f = 3) -->第 1 列 (c = 5 - 3 - 1)
第 4 行 (f = 4) -->第 0 列(c = 5 - 4 - 1)
The key to understanding this is the
if
statement:The two nested loops iterate over rows (using
f
as an index) and for each row, over columns (usingc
as an index).So each iteration, you test if the row number (that is
f
) is equal to the column number reversed (that isc
subtracted from the total number of columns -columnas
). The reason you test for the column number reversed is because you want to add from bottom left to top right, which is the same as adding from top-right to bottom left.One thing to note is that a matrix diagonal only makes sense for a square matrix which means the number of columns needs to be same as the number of rows (in your algorithm
filas
should equalcolumnas
).So, assuming a 5x5 matrix:
Row 0 (f = 0) --> Column 4 (c = 5 - 0 - 1)
Row 1 (f = 1) --> Column 3 (c = 5 - 1 - 1)
Row 2 (f = 2) --> Column 2 (c = 5 - 2 - 1)
Row 3 (f = 3) --> Column 1 (c = 5 - 3 - 1)
Row 4 (f = 4) --> Column 0 (c = 5 - 4 - 1)
不需要双循环。
mxm 矩阵:
There's no need for a double loop.
m x m matrix: