【发布时间】:2015-03-10 03:31:13
【问题描述】:
这是我的作业问题:
编写一个程序,模拟多次滚动一组六面骰子。程序应该使用字典来记录结果,然后显示结果。
输入:程序应提示输入掷骰子的次数和掷骰子的次数。
输出:
该程序将显示每个可能的值被滚动了多少次。输出的格式必须如下所示:
第一列是掷骰子时显示的数字。括号仅根据需要的宽度,括号内的数字是右对齐的。请注意下面示例运行中的最小值和最大值。
第二列是该值被滚动的次数。此列右对齐。
最后一列是数字滚动次数的百分比。百分比显示精确到小数点后一位。
这是我目前的代码:
import random
from math import floor, ceil
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
rand = float(0)
rolltotal = int(input("How many times do you want to roll? "))
q = 0
while q < rolltotal:
q = q + 1
rand = ceil(6*(random.random()))
if rand == 1:
one = one + 1
elif rand == 2:
two = two + 1
elif rand == 3:
three = three + 1
elif rand == 4:
four = four + 1
elif rand == 5:
five = five + 1
else:
six = six + 1
total = one + two + three + four + five + six
print("[1]", one, " ",round(100*one/total, 1),"%")
print("[2]", two, " ",round(100*two/total, 1),"%")
print("[3]", three, " ",round(100*three/total, 1),"%")
print("[4]", four, " ",round(100*four/total, 1),"%")
print("[5]", five, " ",round(100*five/total, 1),"%")
print("[6]", six, " ",round(100*six/total, 1),"%")
我的问题是:我只知道如何掷骰子。我怎样才能得到不止一个。
【问题讨论】:
-
你做得很好。您需要在循环内多次执行第一部分(查找“控制流”或“for 循环”)。 (为了更高级,看看是否有办法不需要六个变量一、二、三等。想想这个问题,“将其更改为 10 面骰子而不是6 面的?”)
-
您应该阅读有关 python dictionaries 的信息,因为您的家庭作业明确需要使用它们。
-
注意 random() 可以返回 0,所以你的 ceil() 不太正确。试试用 floor 代替,看看能不能得到 1-6 个。
-
其实你应该使用
random.randint(1,6) -
@GWW 似乎他在这里使用 Python 3,所以更好的字典链接是:diveintopython3.org/native-datatypes.html#dictionaries
标签: python