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

455 次瀏覽

開啟你的 職業

完成該課程獲得認證

開始
廣告
© . All rights reserved.