题解 | 点到直线距离 叉乘,并避免除以0

点到直线距离

https://www.nowcoder.com/practice/1bcdd78060e54812a9c47ebe40c6af65

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Line:
    def __init__(self, point_a, point_b):
        self.point_a = point_a
        self.point_b = point_b

def get_distance(P, L):
    x0,y0=P.x,P.y
    x1,y1=L.point_a.x,L.point_a.y
    x2,y2=L.point_b.x,L.point_b.y
    numerator = abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1))
    
    # 计算分母:直线AB的长度(向量模长)
    denominator = math.hypot(x2 - x1, y2 - y1)
    
    # 处理直线AB为单点的特殊情况(避免除零)
    if denominator < 1e-9:
        return math.hypot(x0 - x1, y0 - y1)
    
    # 计算距离并返回
    return numerator / denominator

    # TODO: 计算点P到直线L的距离
    pass

































































































































































































def main():
    a, b = map(int, input().split())
    sx, sy, tx, ty = map(int, input().split())
    
    point_a = Point(sx, sy)
    point_b = Point(tx, ty)
    point_c = Point(a, b)
    line = Line(point_a, point_b)
    
    print("{:.2f}".format(get_distance(point_c, line)))

if __name__ == "__main__":
    main()

全部评论

相关推荐

11-03 13:18
门头沟学院 Java
包行:平时怎么刷算法题的哇,字节的手撕听说都很难
字节跳动工作体验
点赞 评论 收藏
分享
10-26 13:03
已编辑
门头沟学院 物流经理
在okr拆解的小太阳...:实习待过,我待的部门氛围很好,基本不加班,双休有保证。
投递正浩创新EcoFlow等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务