【问题标题】:Explain code of exercise Python turtle spiralPython海龟螺旋练习代码讲解
【发布时间】:2018-08-26 14:39:09
【问题描述】:

我是一名编程初学者,正在尝试通过 Python 在线课程做一些简单的练习。我找到了解决方案,但我无法理解代码。你能在下面的一些cmets中解释一下吗? (我会很感激的。)

import turtle from math 
import sin,cos,pi 

t=turtle.Turtle() 
t.speed(0)

n=50  
d=10  
r=0 
x,y = 0, 0 
cur_r = r

for i in range(n): 
    for a in range(1,360, 4): 
        r = cur_r + d*a/360.0 
        a *= pi/180.0 y = r*sin(a) 
        x = r*cos(a) 
        turtle.goto(x,y) 
        cur_r += d

【问题讨论】:

  • @iamL,您的编辑说明说“格式化代码”,但您添加的代码行数与最初的一样多。它仍然没有如图所示运行。

标签: python turtle-graphics spiral


【解决方案1】:

首先,让我们把它从一个不可行的代码片段变成一个工作程序:

import turtle
from math import *

n = 1
d = 2
cur_r = 3

for i in range(n):
    for a in range(1, 360, 4):
        r = cur_r + d * a / 360.0
        a *= pi / 180.0
        x, y = r * cos(a), r * sin(a)
        turtle.goto(x, y)
        cur_r += d

turtle.mainloop()

现在让我们尽可能地解释它。首次导入:

import turtle  # turtle graphics for plotting

from math import *  # get trig routines sine and cosine plus pi constant

下一个全局变量:

n = 1  # number of revolutions around the spiral

d = 2  # growth factor (delta) for spiral radius (in 4 degrees steps)

cur_r = 3  # initial setting of current spiral radius

代码:

for i in range(n):  # for each revolution of the spiral

    for a in range(1, 360, 4):  # angle from 1 to 359 in 4 degree steps

        r = cur_r + d * a / 360.0  # new radius based on current one + delta

        a *= pi / 180.0  # convert angle from degrees to radians

        x, y = r * cos(a), r * sin(a)  # get cartesian coordinates from polar

        turtle.goto(x, y)  # draw a line from previous point to this one

        cur_r += d  # add delta to current radius before repeating process

turtle.mainloop()  # turn control over to tkinter's event handler

错误:

for a in range(1, 360, 4):

应该是:

for a in range(0, 360, 4):

并且“4”可能应该是一个附加变量,而不是硬编码。由于我们已经从数学库中导入了所有内容:

a *= pi / 180.0

可以写成:

a = radians(a)

不清楚这条线的作用:

r = cur_r + d * a / 360.0

这不仅仅是简单的:

r = cur_r

d * a / 360.0 的范围仅从 d/360 到“d”。修改后的代码:

import turtle
from math import cos, sin, radians

revolutions = 1
delta = 2
radius = 3
steps = 4

for i in range(revolutions):
    for angle in range(0, 360, steps):
        angle = radians(angle)
        x, y = radius * cos(angle), radius * sin(angle)
        turtle.goto(x, y)
        radius += delta

turtle.mainloop()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
相关资源
最近更新 更多