0

I have some properties defined by the user, and then I want use them to automatically generate a regular polygon. The properties are centre x, centre y, radius and number of vertices. I would like to know how to calculate the x and y coordinates of all vertices of a regular polygon. I've already tried to do as Calculate coordinates of a regular polygon's vertices discussion. But it always gives me thw wrong coordinates. My current code is as follows (C++):

#define DOUBLE(a) ((a)*(a))

...

if(radius <= 0 || vertices < 3)
  return NULL;

Polygon* poly = new Polygon;

double angle = DOUBLE(M_PI) / vertices;

for(long i = 0; i < vertices; i++)
{
  double a = (angle * i);

  poly->add(centerX + radius * cos(a), centerY + radius * sin(a));
}

return poly;
Community
  • 1
  • 1
Wanderson Silva
  • 1,179
  • 1
  • 17
  • 35

2 Answers2

8

There's an error in your angle calculation.

The angle between each vertex should be 2 * M_PI / vertices.

Obviously your macro:

#define DOUBLE(a) ((a)*(a))

is incorrect.

However in C++ you really shouldn't use macros for such trivial operations anyway - it should at the very most be an inline function, or just the direct formula given above.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

Try

#define DOUBLE(a) ((a) + (a))

or

#define DOUBLE(a) (2 * (a))

You are defining SQUARE(a) under a false identity.

John R. Strohm
  • 7,547
  • 2
  • 28
  • 33