【问题标题】:Distance calculation in turtle gives nothing海龟中的距离计算没有给出任何结果
【发布时间】:2021-10-28 22:22:35
【问题描述】:

我正在尝试计算乌龟从中心点行进的距离,但是当我运行它时它没有给我任何信息:

import math
import turtle
import random

# Starter Code
def randomTurtle():

    for count in range(10):
        choice = random.randint(1,2)
        if (choice==1):
            turtle.forward(random.randint(5, 50))
        elif(choice==2):
            turtle.right(random.randint(1,359))

randomTurtle()
    
def calculateDistance(x,y):

    dist = math.sqrt((0 - x)**2 + (0 - y)**2)
    print(dist)

【问题讨论】:

  • 欢迎您!请收下tour 并阅读How to Ask!另外,创建一个minimal reproducible example 并将其(正确格式化为代码)包含在您的问题中。此外,“不给我任何东西”并不能很好地描述你得到了什么,也不能说明你的期望和原因。
  • 我想你会从阅读how do I ask a good question 中受益,然后回来编辑问题。您能否格式化您的问题,以便所有代码都在代码块中。还有你试过什么?你希望你的输出是什么?你怎么打电话给calculateDistance
  • 看来您没有调用calculateDistance,您可以通过calculateDistance(*turtle.position()) 来实现,或者先定义x, y = turtle.position(),然后调用calculateDistance(x,y),我已经尝试了代码,它工作正常。 .
  • 我正在尝试使用距离公式来计算海龟使用def calculateDistance 移动的距离,我尝试使用x, y = turtle.position() 并首先调用calculateDistance(x,y),但它一直说x 和y 是没有定义,如何使用随机海龟位置作为 (x,y) 并将其插入 Def calculateDistance 。所以基本上如果 'def RandomTurtle' 停在 (5,50), x=5, y= 50 那么这 2 个值将插入等式,答案应该是 50.249378
  • 请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example

标签: python distance turtle-graphics python-turtle


【解决方案1】:

这是使用海龟自己的distance() 方法对您的代码进行的修改,如果需要,您应该能够替换自己的距离公式:

import turtle
from random import choice, randint

def randomTurtle():
    for _ in range(10):
        if choice([True, False]):
            turtle.dot(3, 'red')  # illustrate choices
            turtle.forward(randint(5, 50))
        else:
            turtle.right(randint(1, 359))

def calculateDistance():
    print(turtle.distance((0, 0)))

randomTurtle()
calculateDistance()

turtle.done()

输出

> python3 test.py
79.31702982354314

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    相关资源
    最近更新 更多