python - 如何在没有 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 的垂直线,然后它将无法工作并显示零除法错误
解决方案
我已经想出了办法,所以我会回答我的问题(我希望这样做是可以的)。
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))
推荐阅读
- swift - Swift:为 JPEG 图像获取正确的文件大小
- ruby-on-rails - 如何在 Rails 测试中设置 request_id
- java - 如何提供信任库文件的路径?
- angular - 我可以返回完整的数组,但不能返回数组切片
- android - RxJava2 Emitter.setCancellable 在第二次触摸时取消按钮单击侦听器
- python - 使用 cursor.description 如何获取不同服务器中多个数据库的列名
- selenium-webdriver - 如何从主代码机器在远程/另一台机器上运行 Appium Selenium 移动自动化脚本
- java - Spark:将groupBy输出作为行列表
- reactjs - 提交表单后反应显示消息
- javascript - 将 d3js 画笔从 v3 转换为 v4