Hello, my name is Trevor and this is my first post! I was wondering if someone could give me a hint on an assignment I was given to calculate the area of regular polygons. I know there might have been an easier way to do this but I thought what I have done so far to be okay. However, the pentagon and heptagon values always come out wrong for some reason. Specifically, the pentagon spits out a value of 0 while heptagon is just wrong in general. The long decimals inside their formulas was from constants in their formulas which involved COT and TAN values.
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
usingnamespace std;
int main ()
{
float A;
float total;
float n;
cout <<"Please enter the number of sides for the figure between 3-8 ";
cin >> n;
if (n<3)
{
cout<<"Please enter a valid digit.";
}
if (n>8)
{
cout<<"Please enter a valid digit.";
}
if (n==3)
{
cout <<"The figure you have chosen is equilateral triangle. ";
cout <<"The area formula is: ((sqrt(3))/4)*(A^2) Please enter side length A ";
cin >> A;
float total=((sqrt(3))/4)*(A*A);
cout<<total;
}
if (n==4)
{
cout <<"The figure you have chosen is square. ";
cout <<"The area formula is: A^2. Please enter side length A ";
cin >> A;
float total=(A*A);
cout<<total;
}
if (n==5)
{
cout <<"The figure you have chosen is pentagon. ";
cout <<"The area formula is: (1/4)*(sqrt(5(5+2sqrt(5))))*A^2 Please enter side length A ";
cin >> A;
float total=((1/2)*((A/2)/.726542528)*(A*5));
cout<<total;
}
if (n==6)
{
cout <<"The figure you have chosen is hexagon. " ;
cout <<"The area formula is: ((3*sqrt(3))/2)*(A^2) Please enter side length A ";
cin >> A;
float total=((3*sqrt(3))/2)*(A*A);
cout<<total;
}
if (n==7)
{
cout <<"The figure you have chosen is heptagon. ";
cout <<"The area formula is: (7/4)*(A^2)*cot(180/7) Please enter side length A ";
cin >> A;
float total=((2.0765213965692558)*(A*A)*(7/4));
cout<<total;
}
if (n==8)
{
cout <<"The figure you have chosen is octagon. ";
cout <<"The area formula is: 2*(1+sqrt(2))*(A^2) Please enter side length A ";
cin >> A;
float total=2*(1+(sqrt(2)))*(A*A);
cout<<total;
}
}
More specifically, at line 42, 1/2 uses integer division so the result is always zero. At line 58, 7/4 uses integer division and the result is always 1.
Just wondering, can you figure out how to use the same formula for all the shapes? Not sure whether that is contrary to your assignment or not. Hint: it has to do with triangles, and it will work for any regular polygon with any number of sides :+)
The long decimals inside their formulas was from constants in their formulas which involved COT and TAN values.
C++ can do trig, just #include<cmath> So no need to hard code those values. But you can work out their value with code and make them a const variable.
Prefer to use double rather than float. It won't make any difference for this assignment, but it is a good habit to get into.