
百度对于这个题的不少结果都是一个需要推导才能记住的结论。显然是麻烦的
但其实根本不需要记,这里提供另一种更加容易理解的方法;
前提知识:
2阶行列式:

3阶行列式:

对于平面任意两个向量,求行列式,就是求围成的平行四边形面积。三角形就是求一半的面积。三个点的话相当于把一个点移动到原点。
具体可以看:https://www.bilibili.com/read/cv4236107/
所以问题装换成:

c++ 实现:
#include <iostream>
#include <cmath>
using namespace std;
struct point {
double x, y;
point(double x,double y) {
point::x = x;
point::y = y;
}
};
double triangle(point a, point b, point c) {
return fabs((a.x * b.y - a.x * c.y - b.x * a.y + c.x * a.y + b.x * c.y - c.x * b.y)/ 2.0);
}
int main() {
point a(0,0);
point b(1,0);
point c(0.5,0.5);
cout << triangle(a,b,c);
return 0;
}
判断一个点是否在这个三角形中
思路:若该点在三角形中,则 S(ABC) = S(ABP) + S(ACP) + S(BCP)
实现代码
#include <iostream>
#include <cmath>
using namespace std;
struct point {
double x, y;
point(double x, double y) {
point::x = x;
point::y = y;
}
};
double triangle(point a, point b, point c) {
return fabs((a.x * b.y - a.x * c.y - b.x * a.y + c.x * a.y + b.x * c.y - c.x * b.y) / 2.0);
}
bool in_triangle(point a, point b, point c, point p) {
double s = triangle(a, b, c);
double s1 = triangle(a, b, p);
double s2 = triangle(a, c, p);
double s3 = triangle(b, c, p);
return s == (s1 + s2 + s3) ? true : false;
}
int main() {
point a(0, 0);
point b(1, 0);
point c(0.5, 0.5);
point p(1,1);
cout << in_triangle(a,b,c,p);
return 0;
}