#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct point_tag {
double x;
double y;
} point_t;
bool read_point(FILE *stream, point_t *point)
{
point_t tmp;
if (fscanf(stream, "%lf %lf", &tmp.x, &tmp.y) != 2)
return false;
*point = tmp;
return true;
}
void print_point(FILE *stream, point_t const *point)
{
fprintf(stream, "(%lf, %lf)", point->x, point->y);
}
void print_points(FILE *stream, point_t const *points, size_t num_points)
{
for (size_t i = 0; i < num_points; ++i) {
fprint_point(stream, &points[i]);
putchar('\n');
}
}
size_t read_points(FILE *stream, point_t **points)
{
size_t num_points = 0;
*points = NULL;
for (point_t tmp = { 0 }; fread_point(stream, &tmp);) {
point_t *new_points = realloc(*points, sizeof * new_points * (num_points + 1));
if (!new_points) {
free(*points);
return 0;
}
new_points[num_points++] = tmp;
*points = new_points;
}
return num_points;
}
double area(point_t *points, size_t num_points)
{
double area = 0.;
for (size_t i = 0; i < num_points - 1; ++i)
area += (points[i].x + points[i + 1].x) * (points[i].y - points[i + 1].y);
return area / 2.;
}
int main()
{
point_t *points;
size_t num_points = read_points(stdin, &points);
print_points(stdout, points, num_points);
printf("Area: %f", area(points, num_points));
free(points);
}
Aber bitte beachten daß das nur für sich nicht selbst schneidende Polygone funktioniert. Sonst siehe Bentley–Ottmann algorithm.