Search code examples
c++parametersstructuremath.h

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


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[100];
    int y[100];
};

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) ".

Edit, Correct form:

So yeah, i was making the square bad, the good formula is:

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

And It was another mistake, I was calculating the distance between points, lets say we have (0,0) (5,5) and (0,3), I was calculating the distance between (0,0)-(5,5)-(0,3), but NOT between (0,3)-(0,0). So I add this:

for (int i = 0; (i) < (op.vertex)-1; i++)
{
    res += sqrt(pow(p.x[i + 1] - p.x[i], 2) + pow(p.y[i + 1] - p.y[i], 2));
    index = i;
}
res += sqrt(pow(p.x[index + 1] - p.x[0], 2) + pow(p.y[index + 1] - p.y[0], 2));

So now the distance calculated is something like this (0,0)-(5,5)-(0,3)-(0,0). * These "-" are not a minus.

Thanks Stack Overflow community :)


Solution

  • 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.