温馨提示×

c语言怎么统计指定数字的个数

小亿
319
2024-02-20 10:59:40
栏目: 编程语言

要统计指定数字的个数,可以通过遍历数组或者数字的方式来实现。以下是两种方法的示例:

方法一:统计数组中指定数字的个数

#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;
}

方法二:统计指定数字的个数

#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;
}

以上代码示例可以统计数组中指定数字的个数和整数中指定数字的个数。你可以根据需要选择适合的方法来统计指定数字的个数。

0