Post

根据多边形顶点求面积

给定几个顶点,组成多边形,比如,3 个点就是三角形,4 个点就是四边形,多边形包括凸多边形和凹多边形。

顶点:

\[x_1y_1, x_2y_2, x_3y_3, ..., x_{n-1}y_{n-1}, x_ny_n\]

面积:

\[S = \frac{|(x_1y_2 + x_2y_3 + ... + x_{n-1}y_n + x_ny_1) - (y_1x_2 + y_2x_3 + ... + y_{n-1}x_n + y_nx_1)|}{2}\]

或者

\[S = \frac{|(x_1y_2 - y_1x_2) + (x_2y_3 - y_2x_3) + ... + (x_{n-1}y_n - y_{n-1}x_n) + (x_ny_1 - y_nx_1)|}{2}\]

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double PolygonArea(const vector<vector<double>> &points) {
    const auto n = points.size();
    vector<double> x;
    vector<double> y;
    for (auto &point : points) {
        x.push_back(point[0]);
        y.push_back(point[1]);
    }
    double result = 0;
    for (int i = 0; i < n; ++i) {
        result += x[i] * y[(i + 1) % n];  // + x1y2 ...
        result -= y[i] * x[(i + 1) % n];  // - y1x2 ...
    }
    if (result < 0)
        result = -result;  // abs
    result /= 2.0;  // 1/2
    return result;
}
This post is licensed under CC BY 4.0 by the author.