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.