利用叉积判断直线位置关系,叉积3为 0 则共线或平行,否则相交,设交点 O
则有 P1O × OP2 = P3O × OP4,可以推出公式。
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const double eps = 1e-8;
typedef struct point {
double x;
double y;
}point;
typedef struct v {
point start;
point end;
}v;
double crossProduct(v* v1, v* v2)
{
v vt1, vt2;
double result = 0;
vt1.start.x = 0;
vt1.start.y = 0;
vt1.end.x = v1->end.x - v1->start.x;
vt1.end.y = v1->end.y - v1->start.y;
vt2.start.x = 0;
vt2.start.y = 0;
vt2.end.x = v2->end.x - v2->start.x;
vt2.end.y = v2->end.y - v2->start.y;
result = vt1.end.x * vt2.end.y - vt1.end.y * vt2.end.x;
return result;
}
void lineCross(point p1, point p2, point p3, point p4)
{
v v1, v2, v3;
v1.start = p1;
v1.end = p2;
v2.start = p3;
v2.end = p4;
v3.start = p2;
v3.end = p3;
if(fabs(crossProduct(&v1, &v2)) < eps) {
if(fabs(crossProduct(&v2, &v3)) < eps)
puts("LINE"); //same line
else
puts("NONE"); //parallel
} else {
double a1 = p1.y - p2.y, b1 = p2.x - p1.x, c1 = p1.x * p2.y - p2.x * p1.y;
double a2 = p3.y - p4.y, b2 = p4.x - p3.x, c2 = p3.x * p4.y - p4.x * p3.y;
double x = (b1*c2 - b2*c1) / (a1*b2 - a2*b1);
double y = (a1*c2 - a2*c1) / (b1*a2 - b2*a1);
printf("POINT %.2lf %.2lf\n", x, y); //output the point
}
}
int main()
{
int n;
puts("INTERSECTING LINES OUTPUT");
for(scanf("%d", &n); n--;) {
point p1, p2, p3, p4;
scanf("%lf%lf%lf%lf%lf%lf%lf%lf", &p1.x, &p1.y, &p2.x, &p2.y, &p3.x, &p3.y, &p4.x, &p4.y);
lineCross(p1, p2, p3, p4);
}
puts("END OF OUTPUT");
return 0;
}