用Python 编写程序,用随机函数产生100个0-99范围内的随机整数,统计个位上的数字分别为1.2.3.4.5.6.7.8.9.0.的数的个数并打印出来
时间: 2023-06-20 22:05:20 浏览: 160
产生1~100的随机数字
可以使用Python中的random库来生成随机数,使用循环结构遍历这些随机数,并使用取余运算符%获取个位数,再根据个位数的不同进行计数。
下面是代码实现:
```python
import random
# 初始化各个数字的计数器为0
count_0 = count_1 = count_2 = count_3 = count_4 = count_5 = count_6 = count_7 = count_8 = count_9 = 0
# 生成100个随机整数,并统计个位数
for i in range(100):
num = random.randint(0, 99)
digit = num % 10
if digit == 0:
count_0 += 1
elif digit == 1:
count_1 += 1
elif digit == 2:
count_2 += 1
elif digit == 3:
count_3 += 1
elif digit == 4:
count_4 += 1
elif digit == 5:
count_5 += 1
elif digit == 6:
count_6 += 1
elif digit == 7:
count_7 += 1
elif digit == 8:
count_8 += 1
elif digit == 9:
count_9 += 1
# 输出各个数字的个数
print("个位数为0的数的个数为:", count_0)
print("个位数为1的数的个数为:", count_1)
print("个位数为2的数的个数为:", count_2)
print("个位数为3的数的个数为:", count_3)
print("个位数为4的数的个数为:", count_4)
print("个位数为5的数的个数为:", count_5)
print("个位数为6的数的个数为:", count_6)
print("个位数为7的数的个数为:", count_7)
print("个位数为8的数的个数为:", count_8)
print("个位数为9的数的个数为:", count_9)
```
输出结果可能如下:
```
个位数为0的数的个数为: 11
个位数为1的数的个数为: 12
个位数为2的数的个数为: 11
个位数为3的数的个数为: 12
个位数为4的数的个数为: 12
个位数为5的数的个数为: 10
个位数为6的数的个数为: 10
个位数为7的数的个数为: 5
个位数为8的数的个数为: 7
个位数为9的数的个数为: 10
```
阅读全文