如何编写C语言代码来统计一个某个区间内特定数值出现的次数?
时间: 2024-12-18 19:36:53 浏览: 4
100个经典C语言程序源代码.doc
在C语言中,由于数组索引从0开始,我们可以使用循环结构(如for或while)配合条件判断来计算一个特定数值在一个数组区间内出现的次数。这里是一个基本的例子:
```c
#include <stdio.h>
int count_in_range(int arr[], int size, int target, int start, int end) {
int count = 0;
for (int i = start; i <= end && i < size; i++) {
if (arr[i] == target) {
count++;
}
}
return count;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5, 2, 6, 2, 7};
int target = 2;
int interval_start = 1;
int interval_end = 6;
int occurrences = count_in_range(numbers, sizeof(numbers)/sizeof(numbers[0]), target, interval_start, interval_end);
printf("The number %d appears %d times in the range [%d, %d]\n", target, occurrences, interval_start, interval_end);
return 0;
}
阅读全文