我正在学习使用python进行编程(引用思考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()
正确(对称) 不正确(不对称)
答案 0 :(得分:2)
只需像这样修改您的代码(在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)
答案 1 :(得分:1)
我认为这个问题比你做的更简单。
第一个问题是画一个花瓣改变了龟的标题,你正在尝试做数学将它设置回它开始的地方。在这里我们可以在绘制花瓣之前记录标题并在之后恢复它,没有数学。
第二个问题是当你使用turtle.circle()
的扩展名参数执行此操作时,你可以实现自己的弧代码,这会产生相同的结果但速度更快:
from turtle import Turtle, Screen
def draw_petal(turtle, radius):
heading = turtle.heading()
turtle.circle(radius, 60)
turtle.left(120)
turtle.circle(radius, 60)
turtle.setheading(heading)
my_radius = int(input("What is the radius of the flower? "))
my_petals = int(input("How many petals do you want? "))
bob = Turtle()
for _ in range(my_petals):
draw_petal(bob, my_radius)
bob.left(360 / my_petals)
bob.hideturtle()
screen = Screen()
screen.exitonclick()
<强> USAGE 强>
> python3 test.py
What is the radius of the flower? 100
How many petals do you want? 10
<强>输出强>