为何possibility_1与possibility_2数值始终未变化?求掷硬币模拟代码修复
问题排查与修复方案
核心错误:类型不匹配导致条件永远不成立
你把三个随机数拼接成了字符串(例如"1,1,0"),但判断条件里用的是元组(例如(1,1,0))。字符串和元组属于不同类型,永远不可能相等,所以possibility_1和possibility_2的累加逻辑永远不会触发。额外优化建议
- 避免用
list作为自定义变量名,它是Python内置类型,改用coin_sides这类语义化名称更清晰 - 代码里没用到
math模块,可以直接删除 - 无限
while True循环会一直运行,建议添加模拟次数限制,方便控制运行时长
- 避免用
修复后的完整代码
import random possibility_1 = 0 possibility_2 = 0 # 设置总模拟次数,避免无限循环 total_trials = 1000 current_trial = 0 coin_sides = [0, 1] while current_trial < total_trials: number_1 = random.choice(coin_sides) number_2 = random.choice(coin_sides) number_3 = random.choice(coin_sides) # 用元组存储结果,和判断条件的类型保持一致 number_total = (number_1, number_2, number_3) if number_total == (1,1,0) or number_total == (0,0,1): possibility_1 += 1 if number_total == (1,1,1) or number_total == (0,0,0): possibility_2 += 1 print(f"{number_total} possibility_1={possibility_1} possibility_2={possibility_2}") current_trial += 1 # 输出最终统计概率 print(f"\n模拟结束:") print(f"组合(1,1,0)/(0,0,1)出现概率:{possibility_1/total_trials:.2%}") print(f"组合(1,1,1)/(0,0,0)出现概率:{possibility_2/total_trials:.2%}")
关键修改说明
- 将
number_total改为元组类型,和判断条件中的元组匹配,确保条件判断能正常触发累加 - 添加了模拟次数限制,避免程序无限运行
- 使用f-string简化打印语句,提升可读性
- 增加了最终概率计算输出,更贴合统计需求
内容的提问来源于stack exchange,提问作者YagizWasTaken
相关产品推荐
相关产品推荐

