题解 | 直线与圆交点间距
直线与圆交点间距
https://www.nowcoder.com/practice/396cdc45427847d199c7e279303692bd
我认为这题恶心的地方在于他给出的直线AB中的AB是直线上的任意2点而不是交点,在计算过程中很容易在最后求弦长的时候将半径写为a到b的距离
思路:求出圆心到直线的距离后,利用勾股定理将半径的平方减去距离的平方即可.
#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 c1,c2,c3;
c1=l.point_A.y-l.point_B.y;
c2=-(l.point_A.x-l.point_B.x);
c3=-(c2*l.point_A.y)-c1*l.point_A.x;
double dis = fabs(c1*circle.O.x+c2*circle.O.y+c3)/sqrt(c1*c1+c2*c2);
if(dis == 0){
return 2*circle.r;
}else if(dis == circle.r){
return 0.0;
}
double len;
len = sqrt(circle.r*circle.r - dis*dis);
len = 2*len;
return len;
// 请在这里实现你的代码
}
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;
}