问题描述
所以问题是要我实现一个函数来计算两点之间的距离和斜率。如果斜率是有效值。打印(斜率为XX,距离为XX)但如果是垂直线,则打印(斜率为无穷大,距离为XX)。
这是我的代码:
import math
def points(x1,y1,x2,y2):
slope=(y2-y1)/(x2-x1)
distance=math.sqrt((x2-x1)**2+(y2-y1)**2)
if (x2-x1)==0:
print('The slope is infinity '+' and the distance is '+str(slope))
else:
print('The slope is '+str(slope)+' and the distance is '+str(distance))
代码工作正常,直到遇到 x1==x2 的垂直线,然后它将无法工作并显示零除法错误
解决方法
我已经想出了办法,所以我会回答我的问题(我希望这样做没问题)。
import math
def points(x1,y1,x2,y2):
distance=math.sqrt((x2-x1)**2+(y2-y1)**2)
if x1==x2:
slope='infinity'
print('The slope is '+slope+' and the distance is '+str(distance))
else:
slope=(y2-y1)/(x2-x1)
print('The slope is '+str(slope)+' and the distance is '+str(distance))