题解 | 直线与圆交点间距
直线与圆交点间距
https://www.nowcoder.com/practice/396cdc45427847d199c7e279303692bd
#include <bits/stdc++.h>
using namespace std;
struct point{
double x,y;
point(double A,double B){
x=A,y=B;
}
point() = default;
};
struct line{
point point_A,point_B;
line(point A,point B){
point_A = A,point_B = B;
}
line() = default;
};
struct Circle{
point O;
int r;
Circle(point A,int B){
O=A,r=B;
}
Circle() = default;
};
double getDistance(const Circle& circle, const line& l) {
// 请在这里实现你的代码
double A = l.point_B.y - l.point_A.y;
double B = l.point_A.x - l.point_B.x;
double C = l.point_B.x * l.point_A.y - l.point_A.x * l.point_B.y;
double numerator = abs(A * circle.O.x + B * circle.O.y + C);
double denominator = sqrt(A * A + B * B);
double d = numerator / denominator;
if (d > circle.r) {
// 直线与圆无交点
return 0.0;
} else {
// 应用弦长公式
return 2 * sqrt(circle.r * circle.r - d * d);
}
}
int main() {
double ox, oy, r;
double x1, y1, x2, y2;
cin >> ox >> oy >> r;
cin >> x1 >> y1 >> x2 >> y2;
point center(ox, oy);
Circle circle(center, (int)r);
point p1(x1, y1);
point p2(x2, y2);
line l(p1, p2);
double result = getDistance(circle, l);
cout << fixed << setprecision(6) << result << endl;
return 0;
}
