酷代码 AI
菜单
服务商

C++实现:统计[L, R]范围内数字2出现的次数及代码详解

```cpp #include <iostream> // 统计一个整数中数字2出现的次数 int countTwoInNumber(int num) { int count = 0; while (num > 0) { if (num % 10 == 2) { count++; } num /= 10; } return count; } // 统计[L, R]范围内数字2出现的总次数 int countTwoInRange(int L, int R) { int totalCount = 0; for (int i = L; i <= R; i++) { totalCount += countTwoInNumber(i); } return totalCount; } int main() { int L, R; std::cin >> L >> R; int result = countTwoInRange(L, R); std::cout << result << std::endl; return 0; } ``` 代码解释 1. `countTwoInNumber`函数: - 该函数接收一个整数`num`作为参数。 - 使用`while`循环,不断取出`num`的最后一位数字,判断是否为2,如果是则计数器`count`加1。 - 然后将`num`除以10,去掉最后一位数字,继续循环,直到`num`变为0。 - 最后返回计数器`count`的值。 2. `countTwoInRange`函数: - 该函数接收两个整数`L`和`R`作为参数,表示范围的左右边界。 - 使用`for`循环遍历从`L`到`R`的所有整数。 - 对于每个整数,调用`countTwoInNumber`函数统计其中数字2出现的次数,并累加到`totalCount`中。 - 最后返回`totalCount`的值。 3. `main`函数: - 读取用户输入的两个整数`L`和`R`。 - 调用`countTwoInRange`函数统计[L, R]范围内数字2出现的总次数。 - 输出统计结果。 ######[AI问答 | 489点数解答 | 2026-02-07 17:12:26]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]