In: Computer Science
Study the file polygon.h. It contains the header file for a class of regular polygons. Implement the methods, and provide a driver to test it. It should be in C++
Write a polygon.h file with given instructions for the polygon.cpp file
#include <iostream>
#include <math.h>
using namespace std;
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
int main()
{
float areaP, length, sides;
cout << "\n\n Polygon area program.\n";
cout <<
"---------------------------------\n";
cout << " Enter the number of sides: ";
cin >> sides;
cout << " Enter the length of one side: ";
cin >> length;
areaP = (sides * (length * length)) / (4.0 * tan((M_PI
/ sides)));
cout << " The area of the ploygon is: " <<
areaP << "\n";
cout << " Done..." << endl;
system("pause");
return 0;
}
Also include suitable methods and write a code to provide a driver to test it.
Polygon.h
#include <iostream>
#include <sstream>
#include <cmath>
# define M_PI 3.14159265358979323846
using namespace std;
class Polygon
{
private:
int numSides;
float sideLength;
public:
Polygon();
Polygon(int, float);
int getNumberOfSides();
float getSideLength();
float getArea();
string toString();
};
Polygon.cpp
#include "Polygon.h"
Polygon::Polygon()
{
this->numSides = 0;
this->sideLength = 0.0f;
}
Polygon::Polygon(int sides, float len)
{
this->numSides = sides;
this->sideLength = len;
}
int Polygon::getNumberOfSides(){ return this->numSides; }
float Polygon::getSideLength(){ return this->sideLength; }
float Polygon::getArea()
{
return (numSides * (sideLength * sideLength)) / (4.0 * tan((M_PI / numSides)));;
}
string Polygon::toString()
{
stringstream ss;
ss << "Number of sides: " << this->numSides << endl << "Length of each side: " << this->sideLength << " units" << endl << "Area: " << getArea() << " sq. units" << endl;
return ss.str();
}
main.cpp
#include "Polygon.h"
int main()
{
int numOfSides;
float sideLength;
cout << "\n\n Polygon area program.\n";
cout << "---------------------------------\n";
cout << " Enter the number of sides: ";
cin >> numOfSides;
cout << " Enter the length of one side: ";
cin >> sideLength;
Polygon polygon(numOfSides, sideLength);
cout << endl << polygon.toString() << endl;
}
**************************************************************** SCREENSHOT ***********************************************************