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

   2024-11-04 6970
核心提示:要统计指定数字的个数,可以通过遍历数组或者数字的方式来实现。以下是两种方法的示例:方法一:统计数组中指定数字的个数#inclu

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

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

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

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

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号