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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP