读入一个整数,统计并输出该数中2的个数。要求定义并调用 countdigit ( number , digit ),它的功能是统计整数 number 中数字 digit 的个数。C++
时间: 2024-12-15 10:22:37 浏览: 67
在C++中,你可以通过遍历整数每一位并将每个位与目标数字比较来实现这个功能。这里是一个简单的函数`countDigit`来完成这个任务:
```cpp
#include <iostream>
using namespace std;
// 定义辅助函数 countDigit,统计给定数字 'number' 中指定数字 'digit'
int countDigit(int number, int digit) {
int count = 0;
while (number > 0) {
if (number % 10 == digit) {
count++;
}
number /= 10; // 将 number 向右移一位
}
return count;
}
int main() {
int inputNumber;
cout << "请输入一个整数: ";
cin >> inputNumber;
int targetDigit = 2; // 指定要查找的数字,这里是2
int occurrences = countDigit(inputNumber, targetDigit);
cout << "数字 " << targetDigit << " 在输入的整数 " << inputNumber << " 中出现了 " << occurrences << " 次." << endl;
return 0;
}
```
在这个程序中,我们首先从整数的最低有效位开始(即最后一位),检查它是否等于目标数字,如果相等就增加计数器。然后除以10将数字向右移动一位,直到整个数字都被处理完。
阅读全文
相关推荐

















