0

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

Edited by happygeek: fixed formatting

2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by raj1
0

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.

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.