Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!
tweet

Test for Polygon Area Calculation

By: a guest on May 15th, 2012  |  syntax: C++  |  size: 1.36 KB  |  views: 111  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. #include <iostream>
2.
3. struct Vertex {
4.         float X, Y;
5. };
6.
7. void testFirstPolygon();
8. void testSecondPolygon();
9. void calculateAndPrintArea(const Vertex *polygon, std::size_t vertexCount);
10.
11. int main() {
12.         testFirstPolygon();
13.         testSecondPolygon();
14. }
15.
16. void testFirstPolygon() {
17.         Vertex vertices[] = {
18.           {-10, 0}, {10, 0}, {10, 10}, {-10, 10}, {-10, 0}, {10, 0}
19.         };
20.
21.         std::size_t vertexCount = 4;
22.
23.         calculateAndPrintArea(vertices, vertexCount);
24. }
25.
26. void testSecondPolygon() {
27.         Vertex vertices[] = {
28.           {90, 0}, {110, 0}, {110, 10}, {90, 10}, {90, 0}, {110, 0}
29.         };
30.
31.         std::size_t vertexCount = 4;
32.
33.         calculateAndPrintArea(vertices, vertexCount);
34. }
35.
36. void calculateAndPrintArea(const Vertex *polygon, std::size_t vertexCount) {
37.         float area = 0;
38.
39.         for(std::size_t index = 0; index < vertexCount; index += 2) {
40.                 area += polygon[index + 1].X * (polygon[index + 2].Y - polygon[index].Y);
41.                 area += polygon[index + 1].Y * (polygon[index].X - polygon[index + 2].X);
42.         }
43.         area /= 2;
44.
45.         std::cout << "Polygon Area (method1): " << area << std::endl;
46.
47.         // ------------------------------------------------------------------------
48.
49.         area = 0;
50.
51.         for(std::size_t index = 1; index < vertexCount; ++index) {
52.                 area += polygon[index].X * (polygon[index + 1].Y - polygon[index - 1].Y);
53.         }
54.         area /= 2;
55.
56.         std::cout << "Polygon Area (method2): " << area << std::endl;
57. }
clone this paste RAW Paste Data
Top