/************************************************
Program that calculates the area of a polygon
given it's vertices in the XY plane.
This program uses an algorithm known as the
shoelace algorithm. For more information,
see the wikipedia link:
http://en.wikipedia.org/wiki/Shoelace_algorithm
*************************************************/
#include <iostream>
#include <vector>
using namespace std;
// Function that calculates the absolute value
// of a double type.
double MyAbs(double num)
{
double inv = num * -1;
return (num <= 0) ? inv : num;
}
// Function that calculates the area given a
// vector of vertices in the XY plane.
double CalcArea(vector< pair<double, double> > list)
{
double area = 0; // Total Area
double diff = 0; // Difference Of Y{i + 1} - Y{i - 1}
unsigned int last = list.size() - 1; // Size Of Vector - 1
/* Given vertices from 1 to n, we first loop through
the vertices 2 to n - 1. We will take into account
vertex 1 and vertex n sepereately */
for(unsigned int i = 1; i < last; i++)
{
diff =list[i + 1].second - list[i - 1].second;
area += list[i].first * diff;
}
/* Now We Consider The Vertex 1 And The Vertex N */
diff = list[1].second - list[last].second;
area += list[0].first * diff; // Vertex 1
diff = list[0].second - list[last - 1].second;
area += list[last].first * diff; // Vertex N
/* Calculate The Final Answer */
area = 0.5 * MyAbs(area);
return area; // Return The Area
}
/* Main Function - Sample */
int main()
{
unsigned int vertex = 0;
double x = 0;
double y = 0;
vector< pair<double, double> > v;
cout<<"Enter A Valid Number Of Vertices: " <<endl;
cin >> vertex;
cout<< endl;
while(vertex > 0) {
cout<<"Enter Pair X Y: ";
cin >> x >> y;
v.push_back(make_pair(x, y));
vertex--;
}
cout<<"The Area Of The Polygon Is: " << CalcArea(v) <<endl;
return 0;
}
Area Of Polygon
Page 1 of 11 Replies - 5769 Views - Last Post: 13 August 2010 - 02:22 PM
#1
Area Of Polygon
Posted 08 July 2010 - 01:56 PM
Description: Function That Calculates The Area Of A Polygon Given It's Vertices. This Uses The The Shoelace Algorithm. For More Information: http://en.wikipedia....hoelace_formula
Replies To: Area Of Polygon
#2
Re: Area Of Polygon
Posted 13 August 2010 - 02:22 PM
A little brittle. Vertices must be entered in the correct order (i.e. linearly as on the graph).
Page 1 of 1

New Topic/Question
Reply


MultiQuote



|