统计其中一位数中0~9分别出现的次数
时间: 2023-12-09 11:05:45 浏览: 88
假设我们要统计的数字为n,我们可以将n逐个拆分成个位、十位、百位等等的数字,然后统计每个数字出现的次数即可。
具体地,我们可以用一个长度为10的数组count,count[i]表示数字i出现的次数。然后对于n的每个位上的数字i,我们将count[i]加1。最后遍历count数组输出每个数字出现的次数即可。
以下是Python代码实现:
```
def count_digits(n):
count = [0] * 10
while n > 0:
digit = n % 10
count[digit] += 1
n //= 10
return count
n = 123456789
counts = count_digits(n)
for i in range(10):
print(i, ":", counts[i])
```
输出结果如下所示:
```
0 : 1
1 : 1
2 : 1
3 : 1
4 : 1
5 : 1
6 : 1
7 : 1
8 : 1
9 : 1
```
这表示数字123456789中每个数字都只出现了一次。
相关问题
用C语言写代码,并以ctrl+z作为结束,输入若干正整数,统计其中一位数中0-9分别出现的次数
以下是使用 C 语言编写的代码:
```c
#include <stdio.h>
int main() {
int count[10] = {0}; // 用来存储 0-9 出现的次数
int num;
printf("请输入若干正整数,以 Ctrl+Z 结束输入:\n");
while (scanf("%d", &num) != EOF) {
while (num) {
count[num % 10]++; // 统计最后一位数字出现的次数
num /= 10; // 去掉最后一位数字
}
}
// 输出结果
printf("数字 0-9 分别出现的次数:\n");
for (int i = 0; i < 10; i++) {
printf("%d: %d\n", i, count[i]);
}
return 0;
}
```
在运行程序时,可以依次输入若干正整数,直到使用 Ctrl+Z 结束输入,程序会自动统计其中一位数中 0-9 分别出现的次数,并输出结果。
python统计整数中指定数字出现次数的函数
以下是一个统计整数中指定数字出现次数的Python函数:
```python
def count_digit(n, digit):
count = 0
while n > 0:
if n % 10 == digit:
count += 1
n //= 10
return count
```
其中,`n`是要统计的整数,`digit`是指定的数字。函数使用了一个`while`循环来逐位检查整数中的数字,并统计指定数字出现的次数。在循环中,使用`n % 10`获取整数的个位数,并与指定数字比较。如果相等,则计数器`count`加1。然后使用整数除法`n // 10`将整数的个位数去除,继续循环检查下一位数字。最后返回计数器`count`的值,即指定数字在整数中出现的次数。