判断点是否在三角形内

给定四个点 \(A,B,C,D\),问点 \(D\) 是否在 \(\triangle ABC\) 中(边上或内部)?

考虑叉积可以非常容易的判断:把三角形看首尾相连的三个矢量 \(\overrightarrow {AB}\ \overrightarrow{BC}\ \overrightarrow{CA}\),通过画图可以发现,若点 \(D\) 在三角形内部则一定在三个矢量的同侧(左侧或右侧),反之则一定做不到。

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

struct Point
{
	double x,y;
	
	Point () {}
	Point (double X,double Y) : x(X),y(Y) {}
	Point operator - (const Point a)const { return Point(x-a.x,y-a.y); }
	double operator * (const Point a)const { return x*a.y-y*a.x; }
	void read() { scanf("%lf %lf",&x,&y); }
}A,B,C,D;

int main()
{
	A.read(),B.read(),C.read(),D.read();
	double k1=(B-A)*(D-A),k2=(C-B)*(D-B),k3=(A-C)*(D-C);
	if(k1*k2<0||k1*k3<0) puts("out");
	else puts("in");
	return 0;
}
posted @ 2020-06-27 16:32  With_penguin  阅读(399)  评论(0编辑  收藏  举报