求给定的多边形面积,首先可以分割为数个三角形,分别求面积,最后累加即可。
对上图而言,多边形的面积就是:(S:1,a:2,b:3,c:4,d:5,e:6)
S(1->6) = S(1,2,3) + S(1,3,4) + S(1,4,5) + S(1,5,6)(对凸多边形同样适用)
#include<bits/stdc++.h>
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
/*pair是模版类型,每个pair可以存储任意类型的两个值
对象多个属性:struct,仅两个属性:pair更方便 */
typedef pair<double, double> point;
double det(point p0, point p1, point p2) {
return (p1.first - p0.first) * (p2.second - p0.second) - (p1.second - p0.second) * (p2.first - p0.first);
}
double ploygon_area(int n, point p[]) {
double s = 0.0;
for (int i = 1; i < n - 1; i++)
s += det(p[0], p[i], p[i + 1]);
return 0.5 * fabs(s);
}
int main() {
fio
int n;
double s;
point *pointsc = NULL;
while (cin >> n) {
if (n == 0) break;
points = (point *) malloc(n * sizeof(point));
for (int i = 0; i < n; i++)
cin >> points[i].first >> points[i].second;
s = ploygon_area(n, points);
printf("%.1lf\n", s);
if (points) free(points);
}
}