【问题标题】:How to calculate the average of the sum of 10 random rolled dices如何计算10个随机骰子总和的平均值
【发布时间】:2019-11-12 09:23:36
【问题描述】:

程序将掷 10 个公平骰子(六面),直到这些掷骰的总和为质数且大于或等于 45,然后输出所有这些掷骰总和的平均值。我正在尝试使用 while 循环。这是我到目前为止所拥有的:

import random

# function to generate a random number between 1 and 6
def rollDice():
    roll = random.randint(1,6)
    return roll

for i in range(10):
    print(rollDice(), end = ' ')
# checks if the sum of the dices value is prime
def is_prime(dices):
    total_sum = sum(dices)
    for x in range(2,int(total_sum**0.5)+1):
        if total_sum % x == 0:
            return False
    return True

total_sum = 0
isPrime = False
while isPrime is False or total_sum < 45:
    dices = [rollDice() for dice in range(10)]
    total_sum = sum(dices)
    isPrime = is_prime(dices)

print('Average of the sum of the ten-rolls is {0:.2f}'.format(float(total_sum)/10))

问题是有时我运行程序时,这 10 次滚动的总和不大于 45,无论如何,这些总和的平均值总是等于 4.70

输出应该是:显示 1-6 中的 10 个随机数十次滚动总和的平均值是...

【问题讨论】:

  • 我运行了几次,也得到了不同的值。
  • 你怎么打印出 10 个随机卷,然后你在不同的 10 个随机卷上进行所有计算?

标签: python python-3.x sum average dice


【解决方案1】:

您正在打印的骰子根本不是您在循环结束时拥有的骰子。删除带有print(rollDice()) 的行。 如果你真的想看,最好在代码末尾打印卷。

关于平均值始终为 4.7,这仅仅是因为您没有太多选择 45 到 60 之间的素数(最多 10 个骰子)。可以是 47、53、59。

我现在没有做数学运算,但很明显 59 是组合中最不可能的(你只有 1 个可能的组合,即 9 乘以 6 + 1 乘以 5,所以概率是(1/6 )^10),而 47 似乎是最可能的结果。

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多