Use*_*222 6 python return distance
我仍然是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
Run Code Online (Sandbox Code Playgroud)
Fer*_*ndo 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
Run Code Online (Sandbox Code Playgroud)
您的想法大多是正确的(您的函数逻辑是正确的),但使用函数结果的语法不正确。要获得所需的结果,您可以执行以下操作之一:
将函数调用的结果保存在变量中:
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
Run Code Online (Sandbox Code Playgroud)
或直接打印:
def calculateDistance(x1,y1,x2,y2):
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return dist
print calculateDistance(2,4,6,8)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36375 次 |
| 最近记录: |