题解 | 两直线交点

两直线交点

https://www.nowcoder.com/practice/b14130882e704fd6aa57f8762ae17bac

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

point findMeetingPoint(line line_A, line line_B) {
    // TODO: 在这里输入你的代码,求直线 line_A 与 line_B 的交点

    //已知直线两点,化为一般式,求参数;
    double x1 =line_A.point_A.x,y1=line_A.point_A.y;
    double x2 =line_A.point_B.x,y2=line_A.point_B.y;
    double a1=y2-y1,b1=x1-x2,c1=x2*y1-x1*y2;
    x1=line_B.point_A.x;y1=line_B.point_A.y;
    x2=line_B.point_B.x;y2=line_B.point_B.y;
    double a2=y2-y1,b2=x1-x2,c2=x2*y1-x1*y2;

    //联立一般式方程消元得到交点x,y的公式,带入
    double d=a1*b2-a2*b1;
    if(d==0) return point(-1,-1);
    double x=(b1*c2-b2*c1)/d;
    double y=(a2*c1-a1*c2)/d;
    return point(x,y);

    
}

int main() {
    point A, B, C, D;
    cin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y >> D.x >> D.y;
    line AB = line(A, B);
    line CD = line(C, D);
    point ans = findMeetingPoint(AB, CD);
    cout << fixed << setprecision(12) << ans.x << " " << ans.y;
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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