【发布时间】:2020-09-23 22:20:57
【问题描述】:
我的代码循环遍历二维数组并计算每个整数 1-9 的出现次数,并将它们输出到各自的标签中。
这是我自己写的,并且有点努力去做。
有人可以向我解释为什么会这样吗?特别是这一行:
count[numbers[row, col]]++;
int[ , ] numbers = { { 1, 8 },
{ 4, 5 },
{ 7, 9 },
{ 3, 1 },
{ 9, 3 },
{ 5, 9 },
{ 8, 8 },
{ 9, 9 },
{ 7, 3 },
{ 2, 1 },
{ 5, 4 } };
int[] count = new int [10]; // use this for counting occurrences
// nested loop --- need to loop through the rows, and then the columns
// update the count array with the corresponding values, then increment
for (int row = 0; row < numbers.GetLength(0); row++)
{
for (int col = 0; col < numbers.GetLength(1); col++)
{
count[numbers[row, col]]++;
}
}
oneLabel.Text = count[1].ToString();
twoLabel.Text = count[2].ToString();
threeLabel.Text = count[3].ToString();
fourLabel.Text = count[4].ToString();
fiveLabel.Text = count[5].ToString();
sixLabel.Text = count[6].ToString();
sevenLabel.Text = count[7].ToString();
eightLabel.Text = count[8].ToString();
nineLabel.Text = count[9].ToString();
【问题讨论】:
-
这有助于阐明吗?
int theNumberAtRowCol = numbers[row, col]; count[theNumberAtRowCol] += 1; -
仅供参考,您也可以这样做
foreach(var x in numbers) count[x]++; -
@JohnnyMopp,
count[theNumberAtRowCol] += 1;对我来说很有意义。另一条线对我来说不是很清楚。我一直在与数组作斗争。我知道它只是循环遍历数组中的每个数字并根据遇到的数字递增计数器。我似乎无法想象它足以有信心记住如何去做。 -
@juharr 这看起来要简单得多。这个 foreach 会取代嵌套的 for 循环吗?
-
@Kayair 是的,多维数组在 foreach 中使用时将遍历所有值。所以如果你有一个 3D 甚至 4D 阵列,这将起作用。请注意,
int[][]与int[,]之间的锯齿状阵列不是这样工作的。
标签: c# arrays visual-studio counting