编程之美4.4——点在三角形内

第一种方法:面积相等法
如果点在三角形内部,则如果将三角形的三个顶点与这个点相连所得的三个小三角形的面积之和与原三角形的面积相等
S(A,B,D) + S(A,C,D) + S(B,C,D) = S(A,B,C)
第二种方法:向量叉积法
判断点P3是否在向向P1P2的左边,只需要通过两个向量P1P2、P1P3做叉积就可以判断
P1P2 X P1P3 > 0 则 P3在P1P2左边
P1P2 X P1P3 = 0 则 P3在P1P2上
P1P2 X P1P3 < 0 则 P3在P1P2右边


注: 点(1,3)到(5,1)的向量可以用(4,-2)来表示

V1(x1, y1) X V2(x2, y2) = x1y2 – y1x2

struct point
{
	double x;
	double y;
};

double Distance(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 = Distance(B,C);
	b = Distance(A,C);
	c = Distance(A,B);
	p = (a + b + c) / 2;
	return sqrt((p-a)*(p-b)*(p-c)*p);
}
double CrossProduct(point A, point B, point C)
{
	double result = (B.x - A.x)*(C.y - A.y) - (C.x - A.x) * (B.y - A.y);
	return result;
}

bool IsInTriangle(point A,point B,point C, point D)
{
	double AreaSum = Area(A,B,D) + Area(B,C,D) + Area(A,C,D);
	double AreaSor = Area(A,B,C);
	if(AreaSum - AreaSor > 0.000001)
		return false;
	else
		return true;
}

bool IsInTriangle2(point A, point B, point C, point D)
{
	if(CrossProduct(A,B,D) >= 0 && CrossProduct(B,C,D) >= 0 && CrossProduct(C,A,D) >= 0)
		return true;
	else
		return false;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值