我正在学习用python编程(指thinkpython 2
),并对一个程序感到震惊。问题语句:Python program to draw a symmetric flower after seeking the size of and number of petals from user
。
下面是我编写的代码,只是我无法从数学上正确地计算出每片花瓣之间的夹角(代码接近结束状态的部分)。有人能帮忙吗?
import math
radius=int(input("What is the radius of the flower? "))
petals=int(input("How many petals do you want? "))
#radius=100
#petals=4
def draw_arc(b,r): #bob the turtle,corner-to-corner length (radius) of petal (assume 60 degree central angle of sector for simplicity)
c=2*math.pi*r #Circumference of circle
ca=c/(360/60) #Circumference of arc (assume 60 degree central angle of sector as above)
n=int(ca/3)+1 #number of segments
l=ca/n #length of segment
for i in range(n):
b.fd(l)
b.lt(360/(n*6))
def draw_petal(b,r):
draw_arc(b,r)
b.lt(180-60)
draw_arc(b,r)
import turtle
bob=turtle.Turtle()
#draw_petal(bob,radius)
for i in range(petals):
draw_petal(bob,radius)
bob.lt(360/petals)
turtle.mainloop()
正确(对称) 不正确(不对称)
我认为这个问题比你做的要简单。
第一个问题是画一片花瓣会改变海龟的方向,你要做的是数学运算,让它回到开始的地方。在这里,我们只需在画花瓣之前记录标题,然后再还原它,不需要计算。
第二个问题是,当turtle可以使用
turtle.circle()
的extent参数来实现这一点时,您正在实现自己的arc代码,这会产生相同的结果,但速度要快得多:用法
输出
就这样修改代码(在
draw_petals
中添加b.rt(360/petals-30
,并将bob.lt(360/petals)
更正为360/4
):相关问题 更多 >
编程相关推荐