# Problem calculating the perimeter of a shape by using structures in c++

994 views
-1

The problem consists in that I have to use structures to calculate the perimeter of the shape. The data that is given to me are: the number of sides of the shape, the number of vertices that has the shape and the coordenates X and Y of each vertice.

``````#include <iostream>
using namespace std;
#include <math.h>
``````

## Initializing the struct:

Point save the coordinates of a point (x, y)

``````struct Point
{
int x;
int y;
};
``````

Polygon save the number of sides and vertices that will have the shape

``````struct Poligon
{
int sides;
int vertex;
};

void InputVertexsPoligon(struct Point &p, struct Polygon &op);
float PerimeterPoligon(struct Point &p, struct Polygon &op);
``````

## Declaration of variables and Calling the functions:

``````int main()
{
struct TPunt p;
struct TPoligon op;
float num;

InputVertexsPoligon(p, op);
num = PerimeterPoligon(p, op);

cout << "Perimetre del poligon: " << num << endl;

system("PAUSE");
return 0;
}
``````

Here I make my input of the number of vertices, and therefore, the (x, y) coordenates for each vertice.

`````` void InputVertexsPoligon(struct Point &p, struct Polygon &op)
{
cin >> op.vertex;
for (int i = 0; i < op.vertex; i++)
{
cin >> p.x[i]; cin >> p.y[i];
}

}
``````

And finally, I use the distance between two points formula and by summing all of them until (x[i + 1]) and (y[i + 1]) are equal to the number of vertices.

``````float PerimeterPoligon(struct Point &p, struct Polygon &op)
{
float res = 0;
for (int i = 0; (i+1) < op.vertex; i++)
{
res += sqrt(((pow(p.x[i + 1],2)) - pow(p.x[i], 2)) + (pow(p.y[i + 1], 2) - pow(p.y[i], 2)));
}
return res;
}
``````

So, the problem is that something is wrong, the output of the result of calculating the perimeter in the last function, is " -nan(ind) ".

Most likely you are taking the square root of a negative number. Have you tried stepping through your code with a debugger?

7

``````res += sqrt(((pow(p.x[i + 1],2)) - pow(p.x[i], 2)) + (pow(p.y[i + 1], 2) - pow(p.y[i], 2)));
``````

This is wrong. You're calculating xi+1^2 - xi^2, but what you need here is (xi+1 - xi)^2 -- the square of the difference, not the difference of the squares.

posted this