C# 程式來計算輸入數字中 1 的個數


我使用了一個數組來加法數字 −

int[] num = new int[] {1, 25, 1, 55, 1};

現在透過迴圈檢視 1,如果有 1,則 6,然後遞增計算出現的次數的變數 −

foreach(int j in num) {
   if (j == 1) {
      cal++;
   }
}

示例

以下是計算輸入數字中 1 的個數的程式碼。

線上演示

using System;
public class Demo {
   public static void Main() {
      int cal = 0;
      int[] num = new int[] {1, 25, 1, 55, 1};
      Console.WriteLine("Numbers:");
      for (int i = 0; i < 5; i++) {
         Console.WriteLine(num[i]);
      }
      foreach (int j in num) {
         if (j == 1) {
            cal++;
         }
      }
      Console.WriteLine("Number of 1's: ");
      Console.WriteLine(cal);
      Console.ReadLine();
   }
}

輸出

Numbers:
1
25
1
55
1
Number of 1's:  
3

更新於: 19-6 月-2020

457 瀏覽

開始您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.