C言語で特定の数字の数をカウントする方法は何ですか?
指定された数字の数をカウントするには、配列をループしたり数字をカウントしたりする方法があります。以下はその2つの方法の例です:
方法1:特定の数字が配列内にいくつあるかをカウントする。
#include <stdio.h>
int countNumber(int arr[], int size, int target) {
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
count++;
}
}
return count;
}
int main() {
int arr[] = {1, 2, 3, 2, 4, 2, 5};
int target = 2;
int count = countNumber(arr, 7, target);
printf("数字 %d 在数组中出现的次数为:%d\n", target, count);
return 0;
}
方法2:指定された数字の数を数える。
#include <stdio.h>
int countDigit(int num, int target) {
int count = 0;
while (num > 0) {
if (num % 10 == target) {
count++;
}
num /= 10;
}
return count;
}
int main() {
int num = 123452;
int target = 2;
int count = countDigit(num, target);
printf("数字 %d 在 %d 中出现的次数为:%d\n", target, num, count);
return 0;
}
上記コード例では、配列内の特定の数字の数や整数内の特定の数字の数をカウントすることができます。必要に応じて適切な方法を選択して、特定の数字の数をカウントしてください。