如何使用Python中的返回方法计算两点之间的距离?

问题描述 投票:0回答:10

我对Python还是个新手,一直在努力掌握它的窍门。我一直在尝试学习简单的返回方法,但我似乎无法掌握它的窍门。 我一直试图找到两点之间的距离,这就是我到目前为止所得到的。 如果有人能帮我解决这个问题,那将非常有帮助!谢谢!

import math

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

calculateDistance(2,4,6,8)

print calculateDistance
python return distance
10个回答
12
投票

为什么不使用 math.hypot() 来计算距离?

>>> import math
>>> p1 = (3, 5)  # point 1 coordinate
>>> p2 = (5, 7)  # point 2 coordinate
>>> math.hypot(p2[0] - p1[0], p2[1] - p1[1]) # Linear distance 
2.8284271247461903

1
投票

将结果存储在变量中

import math

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

distance = calculateDistance(2,4,6,8)

print distance

或直接打印结果

import math

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

print calculateDistance(2,4,6,8)

0
投票

您的想法大多是正确的(您的函数逻辑是正确的),但使用函数结果的语法不正确。要获得所需的结果,您可以执行以下操作之一:

将函数调用的结果保存在变量中:

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

some_variable = calculateDistance(2,4,6,8)

print some_variable

或直接打印:

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

print calculateDistance(2,4,6,8)

0
投票
print calculateDistance(2,4,6,8)

将其视为数学中的函数。将函数调用放在需要其值的位置。或者,您可以将值存储在变量中:

dist = calculateDistance(2,4,6,8)
print dist

(这不像数学那样工作。)


0
投票

我不知道什么是“返回方法” - 你这里有一个简单的函数。

不过,您正在做的是调用它,但不对结果执行任何操作:然后打印实际的函数本身,而不是结果。

您可能的意思是:

distance = calculateDistance(2,4,6,8)
print distance

甚至

print calculateDistance(2,4,6,8)

0
投票

想象 Python 运行到函数调用 (

calculateDistance(2, 4, 6, 8)
),评估该函数,并且实际上只是将代码行
calculateDistance(2, 4, 6, 8)
替换为函数返回的数字,比方说
7

因此,在一行中单独键入

calculateDistance(2, 4, 6, 8)
与在一行中单独键入
7
一样。您需要使用该值做一些事情,例如将其存储在变量中

dist = calculateDistance(2, 4, 6, 8)



或者立即打印

print calculateDistance(2, 4, 6, 8)


    


0
投票
所以我不确定你的错误是什么。

如果您想要号码:

def calcdist(x, y, x1, y1): return math.sqrt((x-x1)**2 + (y2-y1)**2) dist = calcdist(#, #, #, #) print dist

现在你正在返回函数

math.sqrt(...)

因此,当您使用 2, 4, 6, 8 调用计算距离时,我认为您将返回一个具有该函数和 4 个参数的对象。

祝你好运


0
投票
在 Eclipse PyDev 中,您可以像这样进行操作:

import math p1 = (2, 4) p2 = (6, 8) dist = math.hypot(p2[0] - p1[0], p2[1] - p1[1]) print (dist)
    

0
投票
import math x1 = int(input("Enter x co-ordinate of 1st point:")) y1 = int(input("Enter y co-ordinate of 1st point:")) x2 = int(input("Enter x co-ordinate of 2nd point:")) y2 = int(input("Enter y co-ordinate of 2nd point:")) def distance_calc(a1,b1,a2,b2): d = math.sqrt((a2-a1)**2 + (b2-b1)**2) print(f"\nDistance: {d}") distance_calc(x1,y1,x2,y2)
    

0
投票
导入数学

x1 = int(input("请输入第一个点的 x 坐标:")) y1 = int(input("请输入第一个点的 y 坐标:"))

x2 = int(input("输入第二点的 x 坐标:")) y2 = int(input("请输入第二点的 y 坐标:"))

def distance_calc(a1, b1, a2, b2): d = math.sqrt((a2 - a1) ** 2 + (b2 - b1) ** 2) 打印(f” 距离:{d}")

使用提供的坐标调用函数

距离计算(x1,y1,x2,y2)

© www.soinside.com 2019 - 2024. All rights reserved.