用相同的数字填充二维数组的列

本文关键字:二维数组 填充 数字 | 更新日期: 2023-09-27 18:33:35

>我正在尝试创建一段代码,最后会显示这一点

1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4 
5 5 5 5 5

但我写的却表明了这一点

1 1 1 1 1
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0
5 0 0 0 0

这是我写的代码

int col, lig, test;
col = 0;
test = 0;
for (lig = mat.GetLowerBound(0); lig <= mat.GetUpperBound(0); lig++)
{
    mat[lig, col] = 1 + test++;
}
for (col = mat.GetLowerBound(0) + 1; col <= mat.GetUpperBound(0); col++)
{
    mat[0, col] = mat[0, col] + 1;
}

我已经尝试了多种方法,但没有一件奏效,我可以修改什么以使其产生我想要的结果?

用相同的数字填充二维数组的列

你的代码有几个问题:

  • 您正在检查数组在维度 0 中的边界以进行第二个循环(对于 col (,但在数组的第 1 维度中使用col:您应该改用 GetLowerBound(1)GetUpperBound(1)。这不是问题,因为您有一个方形数组,但您应该注意。
  • 您需要在行和列上使用嵌套循环,而不是两个单独的 j 循环。你的代码正在执行你告诉它的事情:
    • 在第一个循环中,您设置了mat[lig, col]col为零,因此您只在第一列中设置值。通过在循环声明ligcol(请参阅下面的代码(,您可以避免此错误。
    • 在第二个循环中,您设置mat[0, col]只会更改第一行中的值。
    • 此外,您将在mat.GetLowerBound(0) + 1处启动第二个循环,这将错过第一个元素。大概您是故意这样做的,因为它将元素 (0,0( 设置为 2。

您需要的代码是:

int test = 0;
for ( int lig = mat.GetLowerBound(0); lig <= mat.GetUpperBound(0); lig++ )
{
    test++;
    for ( int col = mat.GetLowerBound(1); col <= mat.GetUpperBound(1); col++ )
        mat[lig, col] = test;
}

您可以通过注意始终lig + 1 test并完全消除test来进一步简化这一点:

for ( int lig = mat.GetLowerBound(0); lig <= mat.GetUpperBound(0); lig++ )
{
    for ( int col = mat.GetLowerBound(1); col <= mat.GetUpperBound(1); col++ )
        mat[lig, col] = lig + 1;
}