C# 程序用于计算输入数字中 1 的数量

csharpserver side programmingprogramming更新于 2025/9/24 9:01:00

我使用数组 − 添加了数字

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

相关文章