Онлайн компилятор C

#include <stdio.h> #include <string.h> int count_between(int from, int to, int size, int a[]){ int counter = 0; for(int current= from; current<=to; current++){ for(int i=0; i<size; i++){ if(a[i]==current){ counter++; } } } return counter; } int main() { int a[] = {1, 1, 2, 5, 3, 0, 100, 101, 99, 99}; printf("%d", count_between(99, 101, 10, a)); return 0; }
这段代码定义了一个函数 `count_between`,它统计数组 `a` 中数值在闭区间 `[from, to]` 内的元素个数。主函数用数组 `{1,1,2,5,3,0,100,101,99,99}` 测试,统计 99 到 101 之间的数字,预期输出应该是 4(99出现两次,100一次,101一次)。

- 你的外层循环遍历了 `from` 到 `to` 的每一个整数,然后内层循环检查数组中是否有这个数。这种方法虽然能工作,但效率较低,因为如果区间很大(比如从 0 到 1000),循环次数会很多。思考一下:能否只遍历一次数组,直接判断每个元素是否在区间内?

- 注意数组 `a` 中可能包含重复元素,你的方法会正确统计重复值,但外层循环的写法会导致对于每个区间内的整数都扫描整个数组。如果区间内有很多连续整数,而数组很小,这种写法会做很多不必要的检查。