簡體   English   中英

用相同的數字填充2D數組的列

[英]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) 在這里這不是問題,因為您有一個正方形陣列,但是您應該知道。
  • 您需要在行和列上使用嵌套循環,而不是兩個單獨的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;
}

您可以通過注意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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM