【问题标题】:Turtle can't go back to the original point after several loops几圈后乌龟无法回到原点
【发布时间】:2020-09-13 09:18:49
【问题描述】:

这里是代码。我尝试了以下方法。

为什么会这样?谁能解释一下?

import turtle


turtle.penup()
turtle.setposition(0,300)
turtle.pendown()

turtle.pencolor("red")

turtle.speed(10)

for i in range(6 , 15, 2):

    step = int(360 / i)

    turtle.setheading(int(90 - (180 - step)/2))
    

    for j in range(1, 1 + i):

        turtle.right(step)

        turtle.forward(10*i)
        
turtle.exitonclick()

这是因为计算中的浮点数吗?

【问题讨论】:

    标签: python python-turtle


    【解决方案1】:

    是的,这是因为 360 不能很好地被 14 整除。这是外循环的最后一次迭代。

    • i = 6:step 是 360 / 6 => 60
    • i = 8: step 是 360 / 8 => 45
    • i = 10:step 是 360 / 10 => 36
    • i = 12:step 是 360 / 12 => 30
    • i = 14:step 是 360 / 14 => 25.714285714

    如果您将代码更改为不将 step 值从浮点数截断为整数,那么它可以正常工作:

    for i in range(6, 15, 2):
        step = 360.0 / i
        turtle.setheading(90 - (180 - step)/2)
    
        for j in range(1, i + 1):
            turtle.right(step)
            turtle.forward(10*i)
    

    【讨论】:

      猜你喜欢
      • 2017-09-27
      • 2011-12-05
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2018-01-25
      • 2017-08-09
      相关资源
      最近更新 更多