gpt4 book ai didi

python - 用 python 画花

转载 作者:行者123 更新时间:2023-11-30 22:42:05 24 4
gpt4 key购买 nike

我正在学习 python 编程(指的是 python 2),并且对一个程序感到震惊。问题陈述:Python 程序在向用户询问花瓣的大小和数量后绘制对称花朵

我想出的代码如下,但我无法在数学上正确地获得每个花瓣之间的角度(靠近末尾的代码状态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()

Expected Flower正确(对称) Incorrect Flower不正确(不对称)

最佳答案

我认为这个问题比你提出的要简单。

第一个问题是绘制花瓣会改变 turtle 的方向,并且您正在尝试进行数学运算以将其设置回开始的位置。这里我们可以在绘制花瓣之前记录标题并在之后恢复它,无需数学。

第二个问题是,当 turtle 可以使用 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()

使用

> python3 test.py
What is the radius of the flower? 100
How many petals do you want? 10

输出

enter image description here

关于python - 用 python 画花,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42265119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com