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.