我正在学习使用python编程(指think python 2
),并被某个程序所震撼。问题陈述:Python program to draw a symmetric flower after seeking the size of and number of petals from user
。
我想出的代码在下面,除了我无法在数学上正确获得每个花瓣之间的角度(在接近结束状态的代码中,该部分表示bob.lt(360/petal)
)。有人可以帮忙吗?
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()
正确(对称)
不正确(不对称)
最佳答案
只需像这样修改代码(在draw_petals
中添加b.rt(360/petals-30
并将bob.lt(360/petals)
更正为360/4
):
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)
b.rt(360/petals-30) # this will take care of the correct angle b/w petals
import turtle
bob=turtle.Turtle()
#draw_petal(bob,radius)
for i in range(petals):
draw_petal(bob,radius)
bob.lt(360/4)