Trying to find the Circumference of a user defined polygon in c++. this is the c
ID: 3886044 • Letter: T
Question
Trying to find the Circumference of a user defined polygon in c++.
this is the code i use to do it
double Length(Point pt1, Point pt2) {
return sqrt((pt2.x - pt1.x) * (pt2.x - pt1.x) + (pt2.y - pt1.y) * (pt2.y - pt1.y));
}
double PolyCircumference(Polygon &thePoly) {
unsigned i = 0;
double Circumference = 0;
for (i = 0; i < thePoly.numSides - 1; i++) {
Circumference += Length(thePoly.v[i], thePoly.v[i + 1]);
}
return Circumference;
However, when I run the program it does not give out the right circumference, 220.122 instead of 27-.122. could someone look at this code and tell me why its running incorrectly? thank you.
Explanation / Answer
The reason you are not getting the answer because you need to use the absolute value of the cordinate differences. Try this out and let me know if you have doubt.
double Length(Point pt1, Point pt2) {
return sqrt((abs(pt2.x - pt1.x) * abs(pt2.x - pt1.x) )+ (abs(pt2.y - pt1.y) * abs(pt2.y - pt1.y)));
}
double PolyCircumference(Polygon &thePoly) {
unsigned i = 0;
double Circumference = 0;
for (i = 0; i < thePoly.numSides - 1; i++) {
Circumference += Length(thePoly.v[i], thePoly.v[i + 1]);
}
return Circumference;