I i have this assignment and i just dont know what to do right now it does not give the the scope i need for every like 3 points its gives me some huge number.
here is the assignment
Write a program that accepts a polygon with n vertices, and calculates its perimeter. To perform the task against, two new types are required:
- The point structure contains the fields: Two integers indicating a reference point (coordinate) in the plane.
- The polygon structure contains the fields: A pointer to an array of type point, the size of the array, and the perimeter of the polygon.
A structure of type must be declared at the beginning of the program polygon, and make an input of n points.
There is no need to sort the points, it will be assumed that order The reception of the points is continuously, so that between every 2 adjacent points there is a side belonging to the polygon.
Below is the list of functions required to perform the task:
- scanPoint
- createPolygon
- distance
- calculateScope
- addPoint
- removePoint
- freeMemory
Note: it must be assumed that the perimeter of a polygon with less than 3 vertices is equal to 0
typedef struct point { int x, y; }point; typedef struct polygon { int n; point* points; double scope; }polygon;
and here is the code i tried to make
int main()
{
int i, n, idx=0;
polygon* poly;
printf("Start Program\n");
poly = createPolygon();
printf("How many points to add: ");
scanf_s("%d",&n);
for (i = 0; i < n; i++)
{
printf("Point #%d: \n", i + 1);
addPoint(poly);
}
printf("Output: Scope of polygon: %.2lf\n", poly->scope);
}
void scanPoint(point* p)
{
printf("\nplease enter x and y data by order-> ");
scanf_s("%d%d", &p->x,&p->y);
}
double distance(point* pA,point*pB)
{
int x = (pA->x) - (pB->x);
int y = (pA->y) - (pB->y);
double d = 0;
d = sqrt(pow(x, 2) + pow(y, 2));
return d;
}
polygon* createPolygon()
{
polygon* New=(polygon*)malloc(sizeof(polygon));
if (New == NULL)
{
printf("the alocation failed");
return NULL;
}
else
{
printf("the alocation sucsess");
New->n = 0;
New->scope = 0;
New->points = NULL;
return New;
}
}
double calculateScope(point* arr, int n)
{
double d = 0;
polygon* prev = arr;
prev->points=(point*)malloc(sizeof(point));
assert(prev);
prev = &prev->points[n-1];
if (n == 0) return d;
d = distance(prev, arr);
return d;
}
int addPoint(polygon* poly)
{
polygon* ptr = poly;
ptr->points = (point*)realloc(ptr->points, (ptr->n + 1)*sizeof(point));
if (ptr == NULL)return 0;
scanPoint(ptr->points);
ptr->scope+=calculateScope(ptr->points,ptr->n);
ptr->n++;
return 1;
}