为什么Python Turtle不完全遵循网格?

发布于 2025-01-25 19:06:00 字数 587 浏览 2 评论 0原文

我偶然发现了这个事实,当时我正在写一个单独的程序时,我很好奇它为什么会发生,以及是否有一种方法可以阻止它发生。

下面的代码是一个简单的程序来说明这一点。乌龟最初似乎遵循网格,即与X或Y轴平行的行进。海龟的印刷坐标的前三个显示了这一点。经过两个方向的变化,如随后的坐标打印输出所示,乌龟似乎从平行到X或Y轴偏向,即使标题应始终是90的倍数。


t = turtle.Turtle()
window = turtle.Screen()

    
def draw_square():
    for i in range(4):
        print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
        t.forward(100)
        t.left(90)


def draw_line():
    for i in range(10):
        t.forward(20)
        print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
    
draw_square()
draw_line()

I stumbled on this fact while working on a separate program I am writing, and am curious about why it happens and whether there is a way to stop it happening.

The code below is for a simple program to illustrate this. The turtle initially seems to follow a grid i.e. travels parallel to either the x or y-axis. This is shown by the first three of the turtles's printed coordinates. After two changes of direction the turtle seems to veer off from parallel to x or y-axis, as shown in subsequent coordinate printouts, even though the heading should always be a multiple of 90.


t = turtle.Turtle()
window = turtle.Screen()

    
def draw_square():
    for i in range(4):
        print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
        t.forward(100)
        t.left(90)


def draw_line():
    for i in range(10):
        t.forward(20)
        print("Coordinates of turtle: (", t.xcor(), ", ", t.ycor(), ")")
    
draw_square()
draw_line()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

×纯※雪 2025-02-01 19:06:00

这似乎只是浮点精度错误。

您看到的差异确实很小,您可以忽略它们。

如果您希望看到更清洁的数字,则可以将它们围成几个小数(在此示例中为3),然后再打印它们:

print("Coordinates of turtle: (", round(t.xcor(), 3), ", ", round(t.ycor(), 3), ")")

It seems to be just a floating-point precision error.

The differences you are seeing are really tiny, you can ignore them.

If you prefer seeing cleaner numbers, you can just round them to a few decimals (3 in this example) before printing them:

print("Coordinates of turtle: (", round(t.xcor(), 3), ", ", round(t.ycor(), 3), ")")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文