#include<cmath> boolisAlmostEqual(double a, double b, double epsilon = 1e-10){ return std::abs(a - b) < epsilon; } doublecalculateArea(Point A, Point B, Point C){ returnabs((B.x - A.x) * (C.y - A.y) - (B.y - A.y) * (C.x - A.x)) / 2.0; }
boolisInsideTriangle(Point A, Point B, Point C, Point P){ double totalArea = calculateArea(A, B, C); double area1 = calculateArea(P, B, C); double area2 = calculateArea(A, P, C); double area3 = calculateArea(A, B, P); returnisAlmostEqual(totalArea, area1 + area2 + area3); }
intmain(){ Point A = {0.0, 0.0}; Point B = {1.0, 0.0}; Point C = {0.5, 1.0}; Point P = {0.3, 0.3}; if (isInsideTriangle(A, B, C, P)) { cout << "Point P is inside the triangle ABC." << endl; } else { cout << "Point P is outside the triangle ABC." << endl; } return0; }
// Function to calculate the cross product of two 2D vectors doublecrossProduct(const Point& a, const Point& b){ return a.x * b.y - a.y * b.x; }
// Function to check if point P lies inside the triangle formed by A, B, and C boolisInsideTriangle(const Point& P, const Point& A, const Point& B, const Point& C){ Point AB = {B.x - A.x, B.y - A.y}; Point BC = {C.x - B.x, C.y - B.y}; Point CA = {A.x - C.x, A.y - C.y};
Point AP = {P.x - A.x, P.y - A.y}; Point BP = {P.x - B.x, P.y - B.y}; Point CP = {P.x - C.x, P.y - C.y};
// Calculate the z components of the cross products double crossAB = crossProduct(AB, AP); double crossBC = crossProduct(BC, BP); double crossCA = crossProduct(CA, CP);
// If all cross products have the same sign (positive or negative), point P is inside the triangle return ((crossAB >= 0 && crossBC >= 0 && crossCA >= 0) || (crossAB <= 0 && crossBC <= 0 && crossCA <= 0)); }
intmain(){ Point P, A, B, C; std::cout << "Enter coordinates of point P (x y): "; std::cin >> P.x >> P.y; std::cout << "Enter coordinates of triangle vertices A, B, and C (x y): "; std::cin >> A.x >> A.y >> B.x >> B.y >> C.x >> C.y;
if (isInsideTriangle(P, A, B, C)) { std::cout << "Point P is inside the triangle formed by A, B, and C." << std::endl; } else { std::cout << "Point P is outside the triangle formed by A, B, and C." << std::endl; }