簡體   English   中英

在C#中,如何遍歷整個2D數組並計算0的數量?

[英]In C#, How can I iterate through a entire 2D Array and count the number of 0s?

我一直在嘗試迭代整個2D數組並計算0的數量。 我怎樣才能做到這一點?

我確定我必須使用以下內容來使程序工作:

  • 使用外部for循環迭代數組的行
  • 使用內部for循環遍歷數組的列
  • 如果matrix[row,col] == 0 ,則增加一個變量
  • 要獲取2D數組的行數,請使用方法matrix.GetLength(0) ,並獲取數組的列數,使用方法matrix.GetLength(1)

這是我到目前為止所嘗試的內容:

public int Test9(int[,] matrix)
{
    int b = 0;
    for (int i = 0; i < matrix.GetLength(0); i++)
        for (int j = 0; j < matrix.GetLength(1); i++)
        {
             b = matrix[i, j];
        }
}

這就是你如何做到的..

 public int Test9(int[,] matrix)
    {
       int zeroCounter = 0;
       for (int i = 0; i < matrix.GetLength(0); i++)
        for (int j = 0; j < matrix.GetLength(1); j++)
        {
                if(matrix[i, j] == 0)
                {
                    zeroCounter++;
                }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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