c++は一つの点が三角形内にあるかどうかを判断する

10198 ワード

#include
#include

using namespace std;

#define err 0.0001

struct Node
{
	float x;
	float y;
};

float TriangleArea(Node p1, Node p2, Node p3)//    
{
	float AB, BC, AC,P;
	AB = sqrt(pow(p2.x - p1.x,2)+ pow(p2.y - p1.y, 2));
	AC = sqrt(pow(p3.x - p1.x, 2) + pow(p3.y - p1.y, 2));
	BC = sqrt(pow(p3.x - p2.x, 2) + pow(p3.y - p2.y, 2));
	P = (AB + AC + BC) / 2;

	return sqrt(P*(P-AB)*(P-AC)*(P-BC));
}

bool IsInTriangle(Node A, Node B, Node C, Node D)
{
	float S1, S2, S3, Ssum;
	S1 = TriangleArea(A, B, D);
	S2 = TriangleArea(A, C, D);
	S3 = TriangleArea(B, C, D);
	Ssum = TriangleArea(A,B,C);

	if (err > fabs(Ssum - S1 - S2 - S3))//     
		return true;
	else
		return false;
}

int main()
{
	Node A, B, C,D;
	A.x = 1; A.y = 0;
	B.x = 3; B.y = 0;
	C.x = 0; C.y = 3;
	D.x = 2; D.y = 0.5;
	cout << "       :" << IsInTriangle(A, B, C, D) << endl;

	system("pause");
	return 0;
}