python - 找到骰子的概率
问题描述
这是我当前的代码:
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”变量作为小数形式。
解决方案
如果我没记错的话应该是(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)}")
推荐阅读
- reactjs - react-chartjs-2 中带有子标签的标签
- node.js - 构建 docker 映像时出现@elastic/elasticsearch 错误
- wpf - 是否有用于静音 CEFSharp 浏览器的 xaml 代码?
- php - 生成 vcard 和 qrcode - 图像未通过
- python - 删除链表Python中的节点
- c - 我如何将 ' 视为普通字母
- pine-script - 如何与特定蜡烛高度交叉移动平均线?脚本
- .net - 为什么我无法从在 AWS ECS 上运行的 .NET Core 应用程序记录任何内容?
- r - 使用 GEOJSON_WRITE 在 R 中创建 GEOJSON 文件
- javascript - CSS 不会影响使用 JavaScript 生成的任何 HTML。我究竟做错了什么?