《编程之美》 4.4 点是否在三角形内
问题:如果在一个二维坐标系中,一直三角形三个点的坐标,那么对于坐标系中的任意一点,如何判断该店是否在三角形内(点在三角形边上也认为在三角形内)?
解法一:如果三角形面积S△ABD+S△BCD+S△CAD > S△ABC,那么D点在△ABC外,如果面积相等那么D点在△ABC内。
代码一:
inline double CalEdge(Point A,Point B)
{
return sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y));
}
double Area(Point A,Point B,Point C)
{
double a,b,c,p;
a = CalEdge(A,B);
b = CalEdge(B,C);
c = CalEdge(C,A);
p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
bool isInTriangle(Point A,Point B,Point C,Point D)
{
//cout<<"Areas : "<<setprecision(3)<<Area(A,B,D)<<" "<<Area(B,C,D)<<" "
// <<Area(C,A,D)<<" "<<Area(A,B,C)<<endl;;
if (Area(A,B,D) + Area(B,C,D) + Area(C,A,D) > Area(A,B,C)) {
return false;
}
return true;
}解法二:利用矢量叉积判断D点是否在AB、BC和CA的同一侧,在同一侧则在三角形内。
代码二:
double Xproduct(Point A,Point B,Point C)
{
return (B.x - A.x) * (C.y - A.y) - (C.x - A.x) * (B.y - A.y);
}
bool isInTriangle2(Point A,Point B,Point C,Point D)
{
//cout<<setprecision(3)<<Xproduct(A,B,D)<<" "<<Xproduct(B,C,D)<<" "
// <<Xproduct(C,A,D)<<endl;
if ((Xproduct(A,B,D) >= 0 && Xproduct(B,C,D) >= 0 && Xproduct(C,A,D) >= 0) ||
(Xproduct(A,B,D) <= 0 && Xproduct(B,C,D) <= 0 && Xproduct(C,A,D) <=0)) {
return true;
}
return false;
}REF:
1,编程之美 4.4 点是否在三角形内

1272

被折叠的 条评论
为什么被折叠?



