c++判断线段是否相交
时间: 2023-05-23 15:02:04 浏览: 499
判断两直线是否相交 C++ MFC
5星 · 资源好评率100%
判断线段是否相交可以使用叉积或者向量。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double x, y;
} Point;
typedef struct {
Point p1, p2;
} Line;
double cross_product(Point a, Point b) {
return a.x * b.y - b.x * a.y;
}
int is_intersected(Line L1, Line L2) {
double c1 = cross_product((Point){L1.p1.x - L2.p1.x, L1.p1.y - L2.p1.y}, (Point){L2.p2.x - L2.p1.x, L2.p2.y - L2.p1.y});
double c2 = cross_product((Point){L1.p2.x - L2.p1.x, L1.p2.y - L2.p1.y}, (Point){L2.p2.x - L2.p1.x, L2.p2.y - L2.p1.y});
double c3 = cross_product((Point){L2.p1.x - L1.p1.x, L2.p1.y - L1.p1.y}, (Point){L1.p2.x - L1.p1.x, L1.p2.y - L1.p1.y});
double c4 = cross_product((Point){L2.p2.x - L1.p1.x, L2.p2.y - L1.p1.y}, (Point){L1.p2.x - L1.p1.x, L1.p2.y - L1.p1.y});
if (c1 * c2 < 0 && c3 * c4 < 0) {
return 1;
} else {
return 0;
}
}
int main() {
Line L1 = {{0, 0}, {1, 1}}, L2 = {{0, 1}, {1, 0}};
if (is_intersected(L1, L2)) {
printf("Line segments intersect.\n");
} else {
printf("Line segments don't intersect.\n");
}
return 0;
}
```
该代码中使用了叉积的方法来判断两条线段是否相交。如果叉积小于零,则表示两条线段相交,否则不相交。
阅读全文