2015-10-27 47 views
1

擲骰6骰子(也稱爲D6),直到它們都出現'1'。計算所花費的卷數。 運行100個這樣的試驗。打印每卷的結果並報告所需的平均卷數。確定在一對骰子上獲得1-1的擲骰的平均數

使用嵌套循環。外循環運行100次試驗;內循環繼續滾動,直到出現1-1。然後更新運行計數並轉到下一個試用版。

import random 
dice1, dice2 = " ", " " 
roll = " " 

for roll in range(1, 101): 
    roll = 0 
    dice1 = random.randint(1, 6) 
    dice2 = random.randint(1, 6) 
    print(dice1, ",", dice2) 
    while dice1 == 1 and dice2 == 1: 
     break 

時2 1的捲起這並不能阻止我需要幫助積累卷號和試驗序號

+0

'break'只有在'while'循環中有效。我假設你想要一個if語句。 –

+0

爲什麼你初始化變量爲字符串,如果你稍後分配給他們的數字? – Barmar

+0

一旦爲你解決這個問題,請記住「接受」你最喜歡的答案。這正確地關閉了StackOverflow的問題。 – Prune

回答

1

的問題是,你的內環真的沒有做任何事情。 你必須給你所描述的工作:繼續滾動兩個骰子,直到它們都出現1.我將概述你描述的邏輯,但是在實現時遇到困難。我將把詳細的工作留給你。 :-)

roll_count = 1 
while not (dice1 == 1 and dice2 == 1): 
    roll both dice 
    increment roll_count 

running_total += roll_count 

您還需要在某處初始化running_total。

這是否讓你失去知覺?

+0

謝謝你的回答!我現在一定明白! – Lucy

0
import random 
from itertools import count 
for roll in range(1, 101): 
    for c in count(1): 
     dice1 = random.randint(1, 6) 
     dice2 = random.randint(1, 6) 
     print(c, ':', dice1, ",", dice2) 
     if dice1 == 1 and dice2 == 1: 
      break