题解 | 直线与圆交点间距

直线与圆交点间距

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;
} 

全部评论

相关推荐

钱嘛数字而已:辅导员肯定不能同意,不然你出事了,他要承担责任。但是,脚和脑子都长在你自己身上,使用它还需要向辅导员报告么? 辅导员必须按流程拒绝你,然后你拿出成年人的态度,做自己的选择。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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