《編程之美》讀書筆記14: 4.4 是否在三角形內


struct Point
{
double x;
double y;
};
static int direction(const Point& a, const Point& b, const Point& p)

{
const double zero=1e-6;
double tmp=(p.x-a.x)*(p.y-b.y)-(p.x-b.x)*(p.y-a.y);
if (tmp > zero) return 1;
if (tmp < -1*zero) return 4;
return 0;
}
bool is_in_triangle(const Point& a, const Point& b, const Point& c, const Point& p)

{
int t= direction(a,b,p)+ direction(b,c,p) + direction(c,a,p);
/**//*
if (t==3 || t==12) return true; //在三角形ABC內
if (t==1 || t==4) return true; //與點A B C之一重合
if (t==2 || t==8) return true; //在三角形ABC邊上。
*/
if (t>=1 && t<=4) return true;
if (t==8 || t==12) return true;
return false; 
//在三角形內a[3]=a[12]=1 在邊上 a[2]=a[8]=1 在頂點a[1]=a[4]=1;
//int a[]={0, 1,1,1,1, 0,0,0, 1, 0,0,0, 1};
//return a[direction(a,b,p)+direction(b,c,p)+direction(c,a,p)];
}



