首页 > 解决方案 > 找到骰子的概率

问题描述

这是我当前的代码:

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”变量作为小数形式。

标签: pythonfor-looprandom

解决方案


如果我没记错的话应该是(count / rolls) * 100。这似乎没有输出0。但是,我刚从幼儿园毕业,所以不要相信我的话。

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 = [random.randint(1, 6) for _ in range(num_dice)]
    x = sum(dice)
    dice_list.append(x)

for i in range(num_dice, (num_dice * 6)+1):
    count = dice_list.count(i)
    print(f"Number of {i}'s rolled: {count} Probability: {round((count / rolls)*100,2)}")

推荐阅读