【发布时间】:2021-05-22 03:12:00
【问题描述】:
这是我当前的代码:
import random
rolls = 1000 # Set number of rolls here.
num_dice = 2 # Set Number of Dice here.
dice_list = []
for i in range(rolls):
dice = sum([random.randint(1, 6) for _ in range(num_dice)])
dice_list.append(dice)
for i in range(num_dice, (num_dice * 6)+1):
count = dice_list.count(i)
count = float(count)
print("Number of {}'s rolled: {} Probability: {}%".format(i,count, round((count / rolls) * 100),2))
我的问题是在计算 i 的百分比时,它会将所有百分比返回为 0%。
更新:当我浏览 StackOverflow 时,我发现它为什么将百分比返回到 0%。要获得实际百分比,您需要将“count”变量作为小数形式。
【问题讨论】:
-
如果您掷出 126 个 8,您的百分比将是
126/1000,即0.126或 12.6%。你关心计算126/(1000 * 100)这是126/100000,这是错误的。你只是在错误的地方有括号。你可能想要(count / rolls) * 100 -
您的“更新”完全不正确。将
count作为一个整数变量是完全可以的,并且从 Python 3 开始完全没有必要将它转换为float。 -
P.S.
sum使用生成器就像使用列表一样容易,因此您的括号是多余的:sum(random.randint(1, 6) for _ in range(num_dice))。 -
P.P.S.如果您仍在使用 Python 2 版本,则需要在问题中指定。 Python 2.7 变成了officially unsupported as of January 1, 2020,当您提出问题时,我们假设它是不合理的。
-
嗨@MarkRansom。我使用的平台是 Pycharm CE (Python 2.7)