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

1239
2024/1/27 10:59:40
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

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

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

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言双向链表的长度如何计算