首頁  >  文章  >  後端開發  >  C#程式:計算輸入數字中1的個數

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

王林
王林轉載
2023-08-23 18:41:031332瀏覽

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

##我已經使用數組添加了數字 -

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

現在循環並查找 1,如果有 1,則增加 6 的變數計算出現次數-

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

範例

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

Live Demo

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&#39;s: ");
      Console.WriteLine(cal);
      Console.ReadLine();
   }
}

輸出

rree

以上是C#程式:計算輸入數字中1的個數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除