I am using a for loop to calculate the distance between the vertices of a polygon
using

for (i=0; i<N, i++)
{
j= (i-1)
result = sqrt (sqr(X-X[j])+sqr(y-y[j]));
}
return result;

This work fine however it doesn't and I cant calculate the distance between the last and first vertice e.g for N=4, calculates N0 to N1, N1 to N2, etc, but doesnt enclose the polygon and calculate N3 to N0
Is there any alteration to this code that will enable this, any help is much appreciated

Recommended Answers

All 2 Replies

There's no way in a for loop, since the (first,last) is a special case. Also, watch your index bounds and maintain your result's aggregate value:

double ClosedPolyPerimeter( double x[], double y[], int N ) {
  int i;
  double result = sqrt( sqr( x[N-1] -x[0] ) +sqr( y[N-1] -y[0] ) );
  for (i = 1; i < N; i++)
    result += sqrt( sqr( x[i] -x[i-1] ) +sqr( y[i] -y[i-1] ) );
  return result;
  }

This code first calculates the special case of distance(N-1,0), then uses the loop to calculate the remaining distance( 1..N-1, 0..N-2 ) and add them each to the result.

Hope this helps.

Now I get it.
Thanks for the quick reply. Your help is very much appreciated!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.