【发布时间】: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