新版第016讲课后作业动动手第2题(模拟抛硬币的终极考验)
本帖最后由 小古比鱼 于 2020-12-29 17:26 编辑原帖地址:https://fishc.com.cn/thread-159296-1-1.html
题目要求:模拟抛硬币,输入次数,打印结果。如果抛硬币的次数小于100,则打印每次的结果,否则不打印。统计最终正面和反面的次数,以及正反面最多出现连续的次数。
以下是小古比鱼编写的代码,感觉比小甲鱼老师提供的参考答案更简洁、更优雅!望各位鱼友走过路过,留下宝贵意见,共同交流进步!
import random
counts = int(input("请输入抛硬币的次数:"))
i = 0
head = tail = 0
head_continuation = tail_continuation = head_max = tail_max = 0
print("开始抛硬币实验……")
while i < counts:
num = random.randint(1, 10)
if num % 2:
head += 1
head_continuation += 1
if head_max < head_continuation:
head_max = head_continuation
tail_continuation = 0
if counts < 100:
print("正面", end=" ")
else:
tail += 1
tail_continuation += 1
if tail_max < tail_continuation:
tail_max = tail_continuation
head_continuation = 0
if counts < 100:
print("反面", end=" ")
i += 1
print("一共模拟了",counts,"次抛硬币,结果如下:")
print("正面:",head,"次\n反面:",tail,"次",sep="")
print("最多连续正面:",head_max,"次\n最多连续反面:",tail_max,"次",sep="")
页:
[1]