使用c语言编写程序,读入n(n<=10),再读入同一平面内一多边形连续n个顶点的坐标(实数),输出该多边形的面积(保留小数点后2位)。需要合理使用以下结构体 struct SPoint //点 { double x; double y; }:
时间: 2024-05-25 19:19:29 浏览: 17
#include <stdio.h>
#include <math.h>
struct SPoint {
double x;
double y;
};
double calcArea(struct SPoint points[], int n);
int main() {
int n;
printf("Enter the number of vertices: ");
scanf("%d", &n);
struct SPoint points[n];
printf("Enter the coordinates of the vertices:\n");
for(int i = 0; i < n; i++) {
printf("Vertex %d: ", i+1);
scanf("%lf %lf", &points[i].x, &points[i].y);
}
double area = calcArea(points, n);
printf("The area of the polygon is %.2lf\n", area);
return 0;
}
double calcArea(struct SPoint points[], int n) {
double area = 0;
for(int i = 0; i < n-1; i++) {
double x1 = points[i].x;
double y1 = points[i].y;
double x2 = points[i+1].x;
double y2 = points[i+1].y;
area += (x1*y2 - x2*y1);
}
double x1 = points[n-1].x;
double y1 = points[n-1].y;
double x2 = points[0].x;
double y2 = points[0].y;
area += (x1*y2 - x2*y1);
area = fabs(area/2);
return area;
}