三點座標,求三角形面積 ,一個點判斷是否在三角形中 c++

給定二維平面中的三個座標點,求三角形面積ios

經過一波向量推導和餘弦函數公式,能推導出來c++

s = |(x1y2 - x1y3 - x2y1 + x3y1 + x2y3 - x3y2) / 2|函數

這最後的公式公式記不住,仍是記上面的行列式吧spa

 

如下是c++實現的代碼code

 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 }

 

判斷一個點是否在這個三角形中blog

思路:若該點在三角形中,則 S(ABC) =  S(ABP) + S(ACP) + S(BCP)io

實現代碼class

 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 }
相關文章
相關標籤/搜索