【发布时间】:2021-03-15 02:20:27
【问题描述】:
我对 python 还很陌生,所以请与我交谈。我正在尝试制作一个海龟直方图,计算各种数字与 100 卷 3 个骰子的次数。但是在用我从掷骰子的试验中得到的总数计算出我的直方图的最大高度之后,直方图的结果与我预期的完全不同。我当前的直方图输出和预期的直方图附在下面。 #请注意,输出会不断变化,因为它有 randrange 提前致谢。
当前代码
from random import randrange
import turtle
totals = dict()
for i in range(3, 19):
totals[i] = 0
# TODO: Set a variable called trials here so we can loop 100 times
trials = 100
for i in range(trials):
first_roll = randrange(1, 7)
second_roll = randrange(1, 7)
third_roll = randrange(1, 7)
total = first_roll + second_roll + third_roll
print(total)
totals[total] += 1
maxheight = 0
for i in range(3, 19):
print(i, totals[i])
if totals[i] > maxheight:
maxheight = totals[i]
scr = turtle.Screen()
t = turtle.Turtle()
t.penup()
t.goto(-138, -175)
t.pendown()
for i in range(3, 19):
t.write(i, align="center")
t.forward(20)
t.penup()
t.goto(-150, -175)
t.pendown()
for i in range(3, 19):
height = int(totals[i] * 300 / maxheight)
t.forward(height)
t.right(90)
t.forward(20)
t.backward(height)
# TODO: In the end, draw the line at the bottom of our histogram
scr.exitonclick()
预期输出
【问题讨论】:
标签: python turtle-graphics python-turtle