点是否在三角形内

《编程之美》 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 点是否在三角形内

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值