Python - 骰子模拟器

3 投票
2 回答
10772 浏览
提问于 2025-04-16 20:49

这是我的作业问题:

写一个程序,模拟多次掷一组六面骰子的过程。这个程序应该用一个字典来记录结果,然后显示这些结果。

输入:程序应该询问要掷多少个骰子,以及要掷多少次。

输出:

程序需要显示每个可能的点数被掷出的次数。输出的格式必须如下所示:

第一列是骰子掷出时显示的点数。括号的宽度只需根据内容调整,括号内的数字要右对齐。注意下面示例运行中的最小值和最大值。

第二列是该点数被掷出的次数。这一列也要右对齐。

最后一列是该点数被掷出的百分比。百分比要保留一位小数。

这是我目前写的代码:

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),"%")

我的问题是:我只知道怎么掷一个骰子,怎么才能掷多个呢?

2 个回答

-1

你可能更想这样做:

loop=True
import random  #This allows python to import built in "random" function.
while loop is True:    
    dice=input("Which sided dice would you like to roll? (You can only choose 4,6 or 12) \n") # "\n" allows python to add a new line.
    if dice=="4":
         print("You have chosen to roll dice 4\nYour score is... \n", random.randint(1,4)) #This allows python to generate a random number from 1 to 4.
    elif dice=="6":
         print("You have chosen to roll dice 6\nYour score is...\n", random.randint(1,6)) #This allows python to generate a random number from 1 to 6.
    elif dice=="12":
        print("You have chosen to roll dice 12\nYour score is...\n", random.randint(1,12)) #This allows python to generate a random number from 1 to 12.
    else: print("Invalid option! Please try again!") 
    loop2=input("Do you want to roll again? (Yes or No) \n")
    if loop2=="yes" or loop2=="Yes": # "or" funtion allows python to accept any of the two answers input by the user.
       loop=True
    else: break    # This function allows program to close.
2
from collections import defaultdict
import random

dice = int(input("How many dice do you want to roll? "))
rolls = int(input("How many times do you want to roll them? "))

irange = xrange
sides = [1,2,3,4,5,6]

d = defaultdict(int)
for r in irange(rolls):
    d[sum( random.choice(sides) for d in irange(dice) )] += 1

total = float(rolls)
for k in sorted(d.keys()):
    print "[%d] %d %.1f%%" % (k, d[k], 100.0*d[k]/total)

这段代码的作用是……

首先,它会……

接下来,它会……

最后,代码会……

总的来说,这段代码的目的是……

如果你有任何疑问,欢迎继续提问!

撰写回答