Please read the new rule regarding the restriction on the use of AI tools. ×

What did I misunderstood about Topcoder Polygon Area tutorial?

Revision en1, by i_am_eating_wa_and_tle, 2024-10-04 10:04:08

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;
}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English i_am_eating_wa_and_tle 2024-10-04 10:04:08 1100 Initial revision (published)