三點坐標,求三角形面積 ,一個點判斷是否在三角形中 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM