题解 | 两直线交点
两直线交点
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){
point p;
double xa = line_A.point_A.x,ya = line_A.point_A.y;
double xb = line_A.point_B.x,yb = line_A.point_B.y;
double xc = line_B.point_A.x,yc = line_B.point_A.y;
double xd = line_B.point_B.x,yd = line_B.point_B.y;
点P弄出来,点ABCD弄出来。
if(fabs((yc-yd)*(xa-xb) - (xc-xd)*(ya-yb)) < 1e-10) {
double distAtoCD = fabs((xd-xc)*(ya-yc) -(xa-xc)*(yd-yc));
double distCtoAB = fabs((xc-xa)*(ya-yb)-(yc-ya)*(xa-xb));
if(distAtoCD<1e-10&&distCtoAB<1e-10){
return point(-1,-1);
}
else{
return point(-1,-1);
}
}
double x0 = ((xc - xd) * (xb * ya - xa * yb) - (xa - xb) *(xd * yc - xc * yd)) / (-(yc - yd) * (xa - xb) + (xc - xd) * (ya - yb)); // 解方程
double y0 = ((xa * yb - ya * xb) * (yc - yd) - (ya - yb) *(xc * yd - yc * xd)) / ((yc - yd) * (xa - xb) - (xc - xd) * (ya - yb));
p.x = x0, p.y = y0;
return p;
}
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(6);
cout << ans.x <<" " << ans.y;
return 0;
}

