我目前在处理2D数组。我希望用计数填充一个2D数组。我已经使用了两个嵌套的for循环来实现这一点。(这可能是最简单的方式,对吧?)
//create count
int count = 1;
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(0); col++)
{
matrix[row, col] = count++;
}
}
我很好奇,是否也有可能只使用一个for循环来填充这个2D数组呢?
我考虑使用一个循环计数行。当行达到数组的末尾时,列将增加1。这可能可以通过使用一些if、if else和else语句来完成,对吗?
这里是否有人知道如何使这个想法实现呢?
matrix.GetLength(0)
。你应该将第二个调用更改为matrix.GetLength(1)
。 - stuartdint GetArrayValue(int row, int col, int colLength) { return (col * colLength) + row }
- user9401448