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