【发布时间】:2015-12-09 15:06:30
【问题描述】:
在 Python 入门课程中,我得到了一个模拟掷骰子的任务
你希望你所有的骰子(总共 5 个)都得到 6,并计算一个人总共掷了多少次才能得到所有的 6。我需要一个循环来模拟这个问题 100.000 次,然后需要将总计数除以 100.000 以获得结果。我知道最终结果应该是 13 左右,但我没有得到,我不知道为什么。
我知道我解决这个问题的方法有问题,但是怎么办?
import random
count1=0
count2=0
count3=0
count4=0
count5=0
loopcounter = 0
for loopcouter in range (1,100000):
dice1=int( random.random()*6)+1
if dice1 != 6:
#reroll
while dice1 != 6:
dice1=int( random.random()*6)+1
#set counter1
count1 = count1+1
else:
count1 = 1
dice2=int( random.random()*6)+1
if dice2 != 6:
#reroll while not six
while dice2 != 6:
dice2=int( random.random()*6)+1
#set counter2
count2 = count2+1
else:
count2 = 1
dice3=int( random.random()*6)+1
if dice3 != 6:
#reroll while not six
while dice3 != 6:
dice3=int( random.random()*6)+1
#set counter3
count3 = count3+1
else:
count3 = 1
dice4=int( random.random()*6)+1
if dice4 != 6:
#reroll while not six
while dice4 != 6:
dice4=int( random.random()*6)+1
#set counter4
count4 = count4+1
else:
count4 = 1
dice5=int( random.random()*6)+1
if dice5 != 6:
#reroll while not six
while dice5 != 6:
dice5=int( random.random()*6)+1
#set counter5
count5 = count5+1
else:
count5 = 1
#print (dice1)
print (count1)
#print (dice2)
print (count2)
#print (dice3)
print (count3)
#print (dice4)
print (count4)
#print (dice5)
print (count5)
allcount = count1+count2+count3+count4+count5
averagecount = int(allcount / 100000)
print ("the total number of throws is",allcount)
print ("the average number of throws is",averagecount)
所以,如果有人能告诉我我做错了什么,那就完美了!
【问题讨论】:
-
您能否澄清一下,您是要始终一次掷 5 个骰子,还是每次都重新掷骰子,直到掷出 6 个骰子?
-
在经典的 yahtzee 游戏中,您只需掷 3 次即可获得 6,但您给了他们无限次滚动,如果您没有获得 5 次 6,那将是失败的。特定 yahtzee 的几率为 1.33%,因此,除以 100000 时,您会期望得到 0.013 的结果。
-
您初始的 if 条件意味着如果您掷出 6 没有其他骰子,实际上没有必要的 if 条件。
-
请不要破坏您的问题;您不能使其他人为回答您所做的工作无效。
标签: python loops simulation dice