【问题标题】:Changing output text for dice rolls更改掷骰子的输出文本
【发布时间】:2020-01-15 10:12:57
【问题描述】:

我正在尝试编写输出如下内容的数字骰子:

1: 1 of 36 卷 2.7777%

2:36 卷中的 2 卷 5.5555%

3:36 卷中的 3 卷 8.3333%

不太清楚该怎么做,但这是我的代码。

import random 
import colorama 

from colorama import Fore, Style 

random.seed()

ROLLED = {i: 0 for i in range(1, 7)}
ITERATIONS = int(input(Fore.LIGHTRED_EX + "How many times would you like to roll the dice?\n"))

Style.RESET_ALL

def probability():
    print(Fore.LIGHTWHITE_EX+"Calculation of probability:")
    for key, count in ROLLED.items():
        print("\t{}: {:.2f}".format(key, count*100./ITERATIONS*1.))


for _ in range(ITERATIONS):#for the inputted range for the iterations
    ROLLED[random.randint(1, 6)] += 1

probability()

我不知道该怎么做。可以使用帮助/提示来找出答案。

【问题讨论】:

  • 现在有什么作用?另外你还没有导入random,所以这不会运行

标签: python python-3.x dice


【解决方案1】:

您可以将滚动的 for 循环更改为:

for roll in range(1,ITERATIONS+1):
    ROLLED[random.randint(1, 6)] += 1
    print("{} of {} Rolls {}%".format(roll,ITERATIONS,round(100/ITERATIONS*roll,4)))

别忘了在某处import random

输出

How many times would you like to roll the dice?
36
1 of 36 Rolls 2.7778%
2 of 36 Rolls 5.5556%
3 of 36 Rolls 8.3333%
4 of 36 Rolls 11.1111%
5 of 36 Rolls 13.8889%
6 of 36 Rolls 16.6667%
7 of 36 Rolls 19.4444%
8 of 36 Rolls 22.2222%
9 of 36 Rolls 25.0%
10 of 36 Rolls 27.7778%
11 of 36 Rolls 30.5556%
12 of 36 Rolls 33.3333%
13 of 36 Rolls 36.1111%
14 of 36 Rolls 38.8889%
15 of 36 Rolls 41.6667%
16 of 36 Rolls 44.4444%
17 of 36 Rolls 47.2222%
18 of 36 Rolls 50.0%
19 of 36 Rolls 52.7778%
20 of 36 Rolls 55.5556%
21 of 36 Rolls 58.3333%
22 of 36 Rolls 61.1111%
23 of 36 Rolls 63.8889%
24 of 36 Rolls 66.6667%
25 of 36 Rolls 69.4444%
26 of 36 Rolls 72.2222%
27 of 36 Rolls 75.0%
28 of 36 Rolls 77.7778%
29 of 36 Rolls 80.5556%
30 of 36 Rolls 83.3333%
31 of 36 Rolls 86.1111%
32 of 36 Rolls 88.8889%
33 of 36 Rolls 91.6667%
34 of 36 Rolls 94.4444%
35 of 36 Rolls 97.2222%
36 of 36 Rolls 100.0%
Calculation of probability:
    1: 13.89
    2: 22.22
    3: 13.89
    4: 22.22
    5: 11.11
    6: 16.67

作为附加信息:

因为您使用的是 python 3,所以 / 是一个“正常”除法。基本上:5/2 = 2.5//是整数除法:5//2 = 2

因此,您可以将 count*100./ITERATIONS*1. 更改为 count*100/ITERATIONS,而无需使用浮动施法。

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2022-01-21
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多