三点坐标,求三角形面积 ,一个点判断是否在三角形中 c++
给定二维平面中的三个坐标点,求三角形面积
通过一波向量推导和余弦函数公式,能推导出来
s = |(x1y2 - x1y3 - x2y1 + x3y1 + x2y3 - x3y2) / 2|
这最后的公式公式记不住,还是记上面的行列式吧
以下是c++实现的代码
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 struct point { 6 double x, y; 7 point(double x,double y) { 8 point::x = x; 9 point::y = y; 10 } 11 }; 12 13 double triangle(point a, point b, point c) { 14 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); 15 } 16 17 int main() { 18 point a(0,0); 19 point b(1,0); 20 point c(0.5,0.5); 21 cout << triangle(a,b,c); 22 return 0; 23 }
判断一个点是否在这个三角形中
思路:若该点在三角形中,则 S(ABC) = S(ABP) + S(ACP) + S(BCP)
实现代码
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 5 struct point { 6 double x, y; 7 point(double x, double y) { 8 point::x = x; 9 point::y = y; 10 } 11 }; 12 13 double triangle(point a, point b, point c) { 14 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); 15 } 16 17 bool in_triangle(point a, point b, point c, point p) { 18 double s = triangle(a, b, c); 19 double s1 = triangle(a, b, p); 20 double s2 = triangle(a, c, p); 21 double s3 = triangle(b, c, p); 22 return s == (s1 + s2 + s3) ? true : false; 23 } 24 25 int main() { 26 point a(0, 0); 27 point b(1, 0); 28 point c(0.5, 0.5); 29 point p(1,1); 30 cout << in_triangle(a,b,c,p); 31 return 0; 32 }