【问题标题】:Trying to simulate 2 dice to know the percentage of same outcome尝试模拟 2 个骰子以了解相同结果的百分比
【发布时间】:2021-08-28 22:58:37
【问题描述】:

所以,我认为它们是代码中某处的逻辑错误。 无论我在输出终端中插入任何数字,输出都保持运行 0%

#dice - count doubles in user - defined number of rounds.. repeated 
import random

#simulate rolling a six sided die and return its value. 
def rollOneDie():
    #generate random numbers from 1 to 6
    thisFace = random.randrange(1,7)
    return thisFace



while True:
    nDoubles = 0
    maxRounds = input(
        "how many rounds do you want to roll?(or ENTER to quit):")
    if maxRounds == '':
        break
    try:
        maxRounds = int(maxRounds)
    except:
        print("please an integer number")
        continue

    for roundNumbers in range(0, maxRounds):
        die1 = rollOneDie()
        die2 = rollOneDie()

    if die1 == die2:
        nDoubles = nDoubles + 1

    percent = (nDoubles * 100.0) / maxRounds
    print('out of ', maxRounds,  'you rolled',
      nDoubles, 'doubles or ', percent, '%')
print('ok byeee')

【问题讨论】:

  • 你想要random.randint(1,7)
  • 这是因为你总是计算 nDoubles。大多数时候是0
  • 你想计算每次迭代骰子上得到相同数字的概率
  • @Sujay 但 nDoubles 的值 = 0
  • @Sujay 我已经尝试了这两种解决方案,但我仍然没有终端中的预期输出

标签: python python-3.x list loops dice


【解决方案1】:

它打印 0% 的原因是检查骰子是否相同的 if 语句位于“滚动”骰子的 for 循环之外,因此仅当最后一次骰子相同时 nDoubles 才增加 1你“滚动”它们。

正确的做法是:

for roundNumbers in range(0, maxRounds):
    die1 = rollOneDie()
    die2 = rollOneDie()

    if die1 == die2:
        nDoubles = nDoubles + 1

另外,你可以写:

nDoubles += 1

而不是

nDoubles = nDoubles + 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 2021-02-12
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2013-12-29
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多