i_am_eating_wa_and_tle's blog

By i_am_eating_wa_and_tle, history, 3 months ago, In English

I have found this tutorial on topcoder Geometry Concept part 1.

In the last section of the tutorial it discusses about area of a polygon. I have took the code and ran it in my IDE but it seems that it give me area = 0 for this coordinates p = {{-1, -1}, {1, 1}, {1, -1}, {-1, 1}}.

What am I missing?

full code

#include <bits/stdc++.h>

using namespace std;

int main() {
    vector<vector<double>> p = {{-1, -1}, {1, 1}, {1, -1}, {-1, 1}};
    double area = 0;
    int N = p.size();
    //We will triangulate the polygon
    //into triangles with points p[0],p[i],p[i+1]

    for (int i = 1; i + 1 < N; i++) {
      double x1 = p[i][0] - p[0][0];
      double y1 = p[i][1] - p[0][1];
      double x2 = p[i + 1][0] - p[0][0];
      double y2 = p[i + 1][1] - p[0][1];
      double cross = x1 * y2 - x2 * y1;
      area += cross;
    }
    cout << abs(area / 2.0) << endl;
    return 0;
}

»
3 months ago, # |
  Vote: I like it +1 Vote: I do not like it

the coordinates should be ordered clockwise or counter-clockwise, I suppose