다음은 삼각형을 피하여 다각형의 면적을 찾는 슬리커 알고리즘을 사용하여 다각형의 면적을 찾는 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