统计正整数中0的个数c++
时间: 2024-02-27 07:55:41 浏览: 25
以下是统计正整数中0的个数的C++代码示例:
```
#include <iostream>
using namespace std;
int countZero(int n) {
int count = 0;
while (n > 0) {
if (n % 10 == 0) {
count++;
}
n /= 10;
}
return count;
}
int main() {
int n;
cout << "请输入一个正整数:";
cin >> n;
cout << "该正整数中0的个数为:" << countZero(n) << endl;
return 0;
}
```
该程序会提示用户输入一个正整数,然后调用`countZero`函数统计该正整数中0的个数,并输出结果。
相关问题
统计正整数指定数字的个数c++
以下是统计正整数指定数字的个数的C++代码实现:
```c++
#include <iostream>
using namespace std;
int count(int n, int num) {
int cnt = 0;
while (n) {
if (n % 10 == num) {
cnt++;
}
n /= 10;
}
return cnt;
}
int main() {
int n, num;
cout << "请输入一个正整数n和指定数字num:" << endl;
cin >> n >> num;
int ans = 0;
for (int i = 1; i <= n; i++) {
ans += count(i, num);
}
cout << "在1~" << n << "中,数字" << num << "出现的次数为:" << ans << endl;
return 0;
}
```
该程序首先通过 `count` 函数统计一个数的十进制表示中指定数字出现的次数,然后在主函数中对1~n中每个数调用 `count` 函数,最后统计出数字num在1~n中出现的总次数。
指针统计正整数指定数字的个数c++
可以使用以下代码来统计一个正整数中指定数字的个数:
```c++
#include <iostream>
using namespace std;
int main() {
int num, digit, count = 0;
cout << "Enter a positive integer: ";
cin >> num;
cout << "Enter the digit to count: ";
cin >> digit;
while (num > 0) {
if (num % 10 == digit) {
count++;
}
num /= 10;
}
cout << "The digit " << digit << " appears " << count << " times in the integer." << endl;
return 0;
}
```
在上述代码中,我们首先输入一个正整数和要统计的数字。然后,我们使用 while 循环来遍历该数字的每一位。如果当前位与要统计的数字相等,则增加计数器。最后,我们输出计数器的值即可。