这篇文章还不错 :http://blog.csdn.net/william001zs/article/details/6213485
1、Onseg() 判断点是否在线段上。
2、Dis() 求点到线段的距离。
3、Meet() 判断两条线段是否相交。
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define N 105
const double eps = 1e-6;
const double Pi = acos(-1.0);
struct Point
{
double x,y;
};
struct Seg
{
Point l1,l2;
};
double Cross(const Point& p1,const Point& p2,const Point& p3,const Point& p4)
{
return (p2.x-p1.x)*(p4.y-p3.y) - (p2.y-p1.y)*(p4.x-p3.x);
}
double Dot(const Point& p1,const Point& p2,const Point& p3,const Point& p4)
{
return (p2.x-p1.x)*(p4.x-p3.x) + (p2.y-p1.y)*(p4.y-p3.y);
}
double Area(const Point& p1,const Point& p2,const Point& p3)
{
return Cross(p1,p2,p1,p3);
}
double Dis(const Point& p1,const Point& p2)
{
return sqrt( 1.0*(p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) );
}
double Dis(const Point& p,const Point& l1,const Point& l2)
{
return fabs(Area(p,l1,l2)) / Dis(l1,l2);
}
bool InRec(const Point& p,const Point& l1,const Point& l2)
{
return p.x >= min(l1.x,l2.x) && p.x <= max(l1.x,l2.x)
&& p.y >= min(l1.y,l2.y) && p.y <= max(l1.y,l2.y);
}
bool OnLine(const Point& p,const Point& l1,const Point& l2)
{
return Cross(p,l1,p,l2) == 0;
}
bool OnSeg(const Point& p,const Point& l1,const Point& l2)
{
return OnLine(p,l1,l2) && InRec(p,l1,l2);
}
bool Meet(const Point& l1,const Point& l2,const Point& l3,const Point& l4)
{
return max(min(l1.x,l2.x),min(l3.x,l4.x)) <= min(max(l1.x,l2.x),max(l3.x,l4.x))
&& max(min(l1.y,l2.y),min(l3.y,l4.y)) <= min(max(l1.y,l2.y),max(l3.y,l4.y))
&& Cross(l3,l2,l3,l4) * Cross(l3,l4,l3,l1) >= 0
&& Cross(l1,l4,l1,l2) * Cross(l1,l2,l1,l3) >= 0;
}