请用C语言统计某个给定范围[L,R]的所有整数中,数字2出现的次数
时间: 2023-06-11 10:10:24 浏览: 98
可以通过以下步骤来统计某个给定范围[L,R]的所有整数中,数字2出现的次数。
1. 定义一个计数器count,初值为0。
2. 从L到R遍历所有整数,对于每个整数num,进行以下计算:
- 定义一个临时变量temp,初值为num。
- 通过对temp取模10,可以获取temp的个位数。
- 如果个位数等于2,则count加1。
- 将temp除以10,将temp的十位数变成个位数,继续执行上一步骤,直到temp变为0。
3. 遍历完所有整数后,count的值即为数字2在[L,R]范围内出现的次数。
以下是C语言代码实现:
```c
#include <stdio.h>
int countDigitTwo(int L, int R) {
int count = 0;
for (int num = L; num <= R; num++) {
int temp = num;
while (temp > 0) {
if (temp % 10 == 2) {
count++;
}
temp /= 10;
}
}
return count;
}
int main() {
int L = 100;
int R = 200;
int count = countDigitTwo(L, R);
printf("数字2在[%d,%d]范围内出现的次数为:%d\n", L, R, count);
return 0;
}
```