# 编程之美阅读笔记

### 1. 判断一个点是否在三角形内部

#include<iostream>
using namespace std;

struct Point
{
int x;
int y;
Point(int x, int y) : x(x), y(y) {}
};

// Function to find orientation of ordered triplet (p, q, r).
// p1p2 x p1p3
int CrossProduct(Point p1, Point p2, Point p3)
{
return (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x);
}

int PointInTriangle(Point p, Point p1, Point p2, Point p3)
{
// Find orientation
int o1 = CrossProduct(p1, p2, p);
int o2 = CrossProduct(p2, p3, p);
int o3 = CrossProduct(p3, p1, p);

// If p is colinear with at least 2 points, then check if it lies
// in the triangle or not
if (o1 == 0 && o2 == 0 && o3 == 0)
{
if (p.x <= max(p1.x, max(p2.x, p3.x)) && p.x >= min(p1.x, min(p2.x, p3.x)) &&
p.y <= max(p1.y, max(p2.y, p3.y)) && p.y >= min(p1.y, min(p2.y, p3.y)))
return 1;
else
return 0;
}

// Check if p is in triangle or not
return (o1 >= 0 && o2 >= 0 && o3 >= 0) || (o1 <= 0 && o2 <= 0 && o3 <= 0);
}

int main() {
Point p1(0, 0), p2(10, 0), p3(5,8);
Point d(-1,0);
if(PointInTriangle(d, p1, p2, p3))
cout << "The point is inside the triangle";
else
cout << "The point is outside the triangle";

return 0;
}