实施避免三角剖分的方法以找出多边形面积的 Slicker 算法的 C++ 程序
这是一个 C++ 程序,用于查找多边形区域,使用避免三角剖分的方法查找多边形区域。
它假定通常的数学惯例中,正 y 向上。在正 y 向下的计算机系统中,可以做的最简单的事情是使用“正 y 向下”坐标逆时针列出顶点。两个作用然后抵消以生成正区域。
函数和伪代码
算法
Begin function Area() is used to calculate area of a polygon take the polygon p as argument. for i = 0 to p.n-1 initialize j = (i + 1) % p.n; calculate t =t+((p.p[i].b * p.p[j].b) - (p.p[j].a * p.p[i].b.)) return t/2 End
示例代码
#include <iostream> using namespace std; const int MAX = 200; class P// to declare variables { private: public: double a, b; }; class Polygon { private: public: P p[MAX]; int n; Polygon()//take the coordinates of each point of polygon { for (int i = 0; i < MAX; i++) P p[i]; } }; double Area(Polygon p)//area calculation { double t = 0; for (int i = 0; i < p.n; i++) { int j = (i + 1) % p.n; t += (p.p[i].b * p.p[j].b) - (p.p[j].a * p.p[i].b); } return t / 2; } int main(int argc, char **argv) { Polygon p; cout << "Enter the number of points in Polygon: "; cin >>p.n; cout << "Enter the coordinates of each point: "; for (int i = 0; i < p.n; i++) { cin >>p.p[i].a; cin >>p.p[i].b; } double a = Area(p); if (a >0)//if area>0 cout << "The Area of Polygon with " << p.n << " points using Slicker Algorithm is : " << a; else cout << "The Area of Polygon with " << p.n << " points using Slicker Algorithm is : " << (a * -1); }
输出
Enter the number of points in Polygon: 6 Enter the coordinates of each point: 1 1 2 2 3 3 4 4 5 5 6 7 The Area of Polygon with 6 points using Slicker Algorithm is : 2.5
广告