Counting Specific Digits in C Programming
To count the number of specified digits, you can achieve this by either traversing through the array or the digits themselves. Below are examples of both methods.
Option: Method 1: Count the number of specific numbers in the array.
#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;
}
Option two: Count the number of specified digits.
#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;
}
The code example above can calculate the number of a specified number in an array and in a specified integer. You can choose an appropriate method to count the specified number as needed.