题解 | 直线与圆交点间距
直线与圆交点间距
https://www.nowcoder.com/practice/396cdc45427847d199c7e279303692bd
import sys
import math
class Point:
def __init__(self, A, B):
self.x = A
self.y = B
class Line:
def __init__(self, A:Point, B:Point):
self.point_A = A
self.point_B = B
class Circle:
def __init__(self, A:Point, B:float):
self.O = A
self.r = B
def calculate_distance(P:Point,L:Line):
circle_x = P.x
circle_y = P.y
x1 = L.point_A.x
y1 = L.point_A.y
x2 = L.point_B.x
y2 = L.point_B.y
if x1 == x2:
return abs(circle_x - x1)
# mx + y + c =0
m = (y1 - y2) / (x1 - x2)
A = -m
B = 1
C = m*x1 - y1
distance = abs(A*circle_x + B*circle_y + C) / math.sqrt(A**2 + B**2)
return distance
def getDistance(circle:Circle, distance:float):
# 请在这里实现你的代码
d = math.sqrt(circle.r**2 - (distance)**2)*2
return d
if __name__ == "__main__":
n = 1
circle_x = 0
circle_y = 0
circle_r = 0
x1 = 0
y1 = 0
x2 = 0
y2 = 0
for line in sys.stdin:
a = line.split()
if n == 1:
circle_x = float(a[0])
circle_y = float(a[1])
circle_r = float(a[2])
n += 1
continue
if n == 2:
x1,y1,x2,y2 = float(a[0]),float(a[1]),float(a[2]),float(a[3])
circle_p = Point(circle_x,circle_y)
A = Point(x1,y1)
B = Point(x2,y2)
L = Line(A,B)
circle = Circle(circle_p,circle_r)
distance = calculate_distance(circle_p,L)
if circle_r == 0:
print(0)
elif circle_r>0:
if distance > circle_r:
print(float(0))
else:
print(getDistance(circle,distance))