首页 > 解决方案 > 如何在没有 zerodivisionerror 的情况下在输出中具有无穷大斜率?

问题描述

所以问题是要我实现一个函数来计算两点之间的距离和斜率。如果斜率是有效值。打印(斜率为 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 的垂直线,然后它将无法工作并显示零除法错误

标签: pythongradientinfinity

解决方案


我已经想出了办法,所以我会回答我的问题(我希望这样做是可以的)。

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))

推荐阅读