1.判断两条线段是否相交
#include <iostream>
using namespace std;
struct Point
{
double x, y;
};
// 判断两条直线是否相交
double determinant(double v1, double v2, double v3, double v4) // 行列式
{
return (v1*v4 - v2 * v3);
}
bool intersect(Point aa, Point bb, Point cc, Point dd)
{
double delta = determinant(bb.x - aa.x, cc.x - dd.x, bb.y - aa.y, cc.y - dd.y);
if (delta <= (1e-6) && delta >= -(1e-6)) // delta=0,表示两线段重合或平行
{
return false;
}
double namenda = determinant(cc.x - aa.x, cc.x - dd.x, cc.y - aa.y, cc.y - dd.y) / delta;
if (namenda > 1 || namenda < 0)
{
return false;
}
double miu = determinant(bb.x - aa.x, cc.x - aa.x, bb.y - aa.y, cc.y - aa.y) / delta;
if (miu > 1 || miu < 0)
{
return false;
}
return true;
}
int main()
{
Point a1, a2, b1, b2;
// 分别指定两条线段的端点
a1.x = 1;
a1.y = 1;
a2.x = 2;
a2.y = 2;
b1.x = 2;
b1.y = 1;
b2.x = 3;