c语言怎么统计指定数字的个数
导读:要统计指定数字的个数,可以通过遍历数组或者数字的方式来实现。以下是两种方法的示例: 方法一:统计数组中指定数字的个数 #include <stdio.h> int countNumber(int arr[], int size...
要统计指定数字的个数,可以通过遍历数组或者数字的方式来实现。以下是两种方法的示例:
方法一:统计数组中指定数字的个数
#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;
}
以上代码示例可以统计数组中指定数字的个数和整数中指定数字的个数。你可以根据需要选择适合的方法来统计指定数字的个数。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c语言怎么统计指定数字的个数
本文地址: https://pptw.com/jishu/633267.html
