นี่คือโปรแกรม C++ เพื่อค้นหาพื้นที่ของรูปหลายเหลี่ยมโดยใช้อัลกอริธึม slicker ที่หลีกเลี่ยง Triangulation เพื่อค้นหาพื้นที่ของรูปหลายเหลี่ยม
มันถือว่าแบบแผนทางคณิตศาสตร์ปกติที่ 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