首页 > 解决方案 > 在 C# Visual Studio 中计算二维数组中整数的出现次数

问题描述

我的代码循环遍历二维数组并计算每个整数 1-9 的出现次数,并将它们输出到各自的标签中。

我自己写了这个,有点努力去做。

有人可以向我解释为什么会这样吗?特别是这一行:

计数[数字[行,列]]++;

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();

标签: c#arraysvisual-studiocounting

解决方案


count[numbers[row, col]]++;

首先,您需要知道 numbers[row, col] 仅访问一个数字,并且正在获取该数字并在 count 数组中使用它;

[0,0][1,0][2,0]
[0,1][1,1][2,1]
[0,2][1,2][2,2]

每个方括号仅代表一个数字。您正在获取该数字并将其放入计数数组中,就像 count [0,0] 但 [0,0] 只是一个像 1 或其他东西的 int。

希望这会有所帮助,我喜欢把它想象成一个 tiktactoe 板。


推荐阅读