[英]Filling columns of a 2D array with the same number
我正在嘗試創建一段代碼,最后將顯示該代碼
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;
}
我已經嘗試了多種方法,但都無濟於事,該如何修改才能得到我想要得到的結果?
您的代碼有些錯誤:
col
)在維度0
中的數組邊界,但是在數組的維度1中使用col
:您應該使用GetLowerBound(1)
和GetUpperBound(1)
。 在這里這不是問題,因為您有一個正方形陣列,但是您應該知道。 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;
}
您可以通過注意test
始終為lig + 1
並完全消除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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.