【问题标题】:Determine average number of roll to get 1-1 on a pair of dice确定在一对骰子上获得 1-1 的平均掷骰数
【发布时间】:2015-10-27 08:14:08
【问题描述】:

掷出一对 6 面骰子(也称为 D6),直到它们都出现“1”。数一数这卷了多少次。 运行 100 次试验。打印出每卷的结果并报告所需的平均卷数。

使用嵌套循环。外循环运行 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 是一个滚动时,这不会停止,我需要帮助累积滚动号和试用号

【问题讨论】:

  • break 只会跳出您拥有的while 循环。我假设你想要一个 if 语句。
  • 如果您稍后将数字分配给变量,为什么还要将变量初始化为字符串?
  • 为您解决此问题后,请记住“接受”您最喜欢的答案。这正确地解决了 StackOverflow 的问题。

标签: python random nested-loops dice cumulative-sum


【解决方案1】:

问题是你的内部循环真的没有做任何事情。 你必须给它你描述的工作:继续掷两个骰子,直到它们都出现 1。我将概述你描述的逻辑,但难以实施。我把详细的工作留给你。 :-)

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

running_total += roll_count

你还需要在某处初始化 running_total。

这会让你摆脱困境吗?

【讨论】:

  • 感谢您的回答!我现在绝对明白了!
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2023-03-15
    • 2021-04-04
    • 2022-07-07
    相关资源
    最近更新 更多