ฉันได้เพิ่มตัวเลขโดยใช้อาร์เรย์แล้ว -
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