Calculating the area of a shape

You need to calculate the area of a two-dimensional shape (triangle or square).

public double GetArea()
{
    double area = default(double);

    for (int i = 0; i < dots.Length - 1; i++)
    {
        area += dots[i].X * dots[i + 1].Y - dots[i].Y * dots[i + 1].X;
    }

    retuen area / 2;
}

I set the location of the points in hourly order or vice versa, but, in my opinion, the area is calculated incorrectly.

Author: Артём Ионаш, 2016-01-17

1 answers

You forgot to add the last segment of the closed polyline to the sum:

public double GetArea()
{
    double area = default(double);

    for (int i = 0; i < dots.Length - 1; i++)
    {
        area += dots[i].X * dots[i + 1].Y - dots[i].Y * dots[i + 1].X;
    }
    // Не забываем, что ломаная должна быть замкнутой:
    area += dots[dots.Length - 1].X * dots[0].Y - dots[dots.Length - 1].Y * dots[0].X;

    return Math.Abs(area) / 2;
}

Your formula is correct: wikipedia.
There is another slightly different, but equally correct (and slightly faster) option: algolist.manual.ru

 3
Author: Dmitry D., 2016-01-17 16:10:19