当前位置: 代码迷 >> 综合 >> [python菜鸟求助] 计算两点之间的距离用不同的写法竟然结果不同
  详细解决方案

[python菜鸟求助] 计算两点之间的距离用不同的写法竟然结果不同

热度:64   发布时间:2024-01-25 08:26:27.0
class Point(object):def __init__(self, x, y):"""点的初始化方法:param x: 横坐标:param y: 纵坐标"""self.x = xself.y = ydef move_to(self, x, y):"""移动到指定位置:param x: 移动后的横坐标:param y: 移动后的纵坐标:return:"""self.x = xself.y = ydef move_by(self, dx, dy):"""增量移动:param x: 沿横轴正方向移动的距离:param y: 沿纵轴正方向移动的距离:return:"""self.x += dxself.y += dydef distance(self, other):"""计算距离:param other: 另一个坐标:return: 距离"""return sqrt((self.x - other.x) ** 2 + (self.x - other.x) ** 2)point1 = Point(3, 0)
point2 = Point(0, 4)
point3 = Point(4, 0)
point4 = Point(0, 3)
print(point1.distance(point2))  # 结果为 4.242640687119285
print(point3.distance(point4))  # 结果为 5.656854249492381

根据勾股定理print出来应该是5才对,求大神解释!

如果把distance方法改成 

    def distance(self, other):"""计算距离:param other: 另一个坐标:return: 距离"""dx = self.x - other.xdy = self.y - other.yreturn sqrt(dx ** 2 + dy ** 2)

则print的结果都是5.0 ,请问这两种写法有啥区别?

 

  相关解决方案