Yuliya
Yuliya

Reputation: 31

Area of Polygon - C++

I'm trying to write a code to calculate the area of a polygon, but it looks like something isn't adding up. Might be that the formula is off, or I need to use the absolute value function?

double polygon_area(int actual_size, double x[], double y[])
{

    printf("In polygon.area\n");                //Initial basic test

    int i;
    double area;

    area = 0.0;

    for (i = 0; i <= max_size; i = i + 1)
    {

        area = (x[i + 1] + x[i]) * (y[i + 1] - y[i]);

        area = (area * 0.50);

    }

    printf("The area of the polygon is %lf  \n", area);

    return (area);
}

Upvotes: 0

Views: 8632

Answers (1)

R Sahu
R Sahu

Reputation: 206577

Problems that I see:

  1. You are computing the area as if there are max_size elements to compute the area from. I think you need to use actual_size.

  2. Since C++ indices for arrays start with 0, they need to stop at actual_size-1, not actual_size. Instead of

    for (i = 0; i <= max_size; i = i + 1)
    

    use

    for (i = 0; i < actual_size; ++i)
    // Using ++i is more idiomatic that using i = i + 1
    
  3. Computation of area is wrong. Replace the lines:

    area = (x[i + 1] + x[i]) * (y[i + 1] - y[i]);
    
    area = (area * 0.50);
    

    by

    area += 0.5*(the area term);
    
  4. Calculation of the area term needs to use wrap around indices. Say you have 5 points. When processing the 5-th point, you have to use indices 4 and 0, not 4 and 5.

    Instead of

    x[i + 1] + x[i]) * (y[i + 1] - y[i]);
    

    use

    x[(i + 1)%actual_size] + x[i]) * (y[(i + 1)%actual_size] - y[i]);
    
  5. The computation for the area term needs to be fixed. Instead of using

    0.5*(x2 + x1) * (y2 - y1))
    

    you need to use:

    0.5*(x1.y2 - x2.y1)
    

Here's a simplified version of the function:

double polygon_area(int actual_size, double x[], double y[])
{
    printf("In polygon.area\n");

    double area = 0.0;

    for (int i = 0; i < actual_size; ++i)
    {
       int j = (i + 1)%actual_size;
       area += 0.5 * (x[i]*y[j] -  x[j]*y[i]);
    }

    printf("The area of the polygon is %lf  \n", area);

    return (area);
}

Upvotes: 5

Related Questions