C# 用相同的数字填充二维数组的列
我正在尝试创建一段代码,它将在最后显示这一点C# 用相同的数字填充二维数组的列,c#,multidimensional-array,C#,Multidimensional Array,我正在尝试创建一段代码,它将在最后显示这一点 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);
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;
}
int col,lig,test;
col=0;
测试=0;
对于(lig=mat.GetLowerBound(0);lig您的代码有一些错误:
- 您正在为第二个循环检查维度
0
中数组的边界(对于col
),但是在数组的维度1中使用col
:您应该使用GetLowerBound(1)
和GetUpperBound(1)
相反。这不是问题,因为您有一个方形数组,但您应该知道
- 您需要在行和列上使用嵌套循环,而不是两个单独的j循环。您的代码正在执行您告诉它的操作:
- 在第一个循环中,您正在设置
mat[lig,col]
,但col
为零,因此您只能在第一列中设置值。通过在循环中声明lig
和col
(请参见下面的我的代码),您可以避免此错误
- 在第二个循环中,您正在设置
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;
}
您的代码有一些问题:
- 您正在为第二个循环检查维度
0
中数组的边界(对于col
),但是在数组的维度1中使用col
:您应该使用GetLowerBound(1)
和GetUpperBound(1)
相反。这不是问题,因为您有一个方形数组,但您应该知道
- 您需要在行和列上使用嵌套循环,而不是两个单独的j循环。您的代码正在执行您告诉它的操作:
- 在第一个循环中,您正在设置
mat[lig,col]
,但col
为零,因此您只能在第一列中设置值。通过在循环中声明lig
和col
(请参见下面的我的代码),您可以避免此错误
- 在第二个循环中,您正在设置
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;
}