判断一个点是否在三角形内
面积法:若点P在三角形ABC内,则三角形ABP+三角形ACP+三角形BCP的面积等于三角形ABC
已知三角形三点坐标ABC,如何求三角形面积呢?
根据叉乘公式,向量A=(x1,y1) ,向量B=(x2,y2),A x B = x1*y2 - x2*y1
此时求得的是向量A和向量B的形成的平行四边形的面积,除以2就是三角形的面积了
代码:
#include <iostream> #include <cstring> #include <queue> #include <cmath> #include <cstdio> #include <algorithm> using namespace std; const double eps = 1e-8; struct point { double x,y; }; double solve(point a,point b,point c) { point A; A.x = b.x-a.x; A.y = b.y-a.y; B.x = c.x-a.x; B.y = c.y-a.y; return (A.x*B.y-B.x*A.y)/2.0; } int main() { point A,B,C,P; cin>>A.x>>A.y; cin>>B.x>>B.y; cin>>C.x>>C.y; cin>>P.x>>P.y; double sum = solve(A,B,C); double k=0; k + = solve(A,B,P); k + = solve(B,C,P); k + = solve(A,C,P); if((k-sum)>eps) cout<<"在三角形外"<<endl; else cout<<"在三角形内"<<endl; return 0; }