About program
Use C++ to calculate area using shoelace formula.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*By Kougmeng 19/07/2022*/ | |
#include <iostream> | |
int main(void) | |
{ | |
float sum = 0.0f; | |
const int number_of_polygon = 7; | |
//List the coordinates in counter - clockwise | |
//and add the first point to the array to make a complete loop | |
float coordinates[number_of_polygon+1][2] = { {1.0f, 2.0f}, {0.0f, 0.0f},{-3.0f, -1.0f}, | |
{3.0f, -2.0f}, {4.0f,2.0f}, {0.0f,3.0f}, {-2.0f,0.0f}, {1.0f,2.0f} }; | |
for (int i = 0; i < number_of_polygon; i++) | |
{ | |
sum += coordinates[i][0] * coordinates[i + 1][1] - coordinates[i + 1][0] * coordinates[i][1]; | |
} | |
float area = sum / 2; | |
std::cout << "The area of the shape is: " << area << std::endl; | |
std::cin.get(); | |
} |
Usage
To calculate area you need to change the variable number_of_polygon to the number of polygon your shape has. And change the coordinates array to the coordinate of each vertices of your shape. You need to list it in counter-clockwise position, and don't forget to add the first vertex to the back of the array to create a loop.
No comments:
Post a Comment