Adam
Adam

Reputation: 485

C++ function calculating the area of a triangle

I have the following function in C++ that is supposed to find the area of a triangle using Heron's formula. I haven't made any mistake in the math but it doesn't produce the right result! I am looking at it for more than 3 hours and I can't find any mistake. What am I missing?

float TriangleArea(float x0, float y0, float x1, float y1, float x2, float y2)
{
    float area_triangle;
    float a, b, c, s;

    a=std::sqrt((x0-x1)*(x0-x1)-(y0-y1)*(y0-y1));
    b=std::sqrt((x1-x2)*(x1-x2)-(y1-y2)*(y1-y2));
    c=std::sqrt((x0-x2)*(x0-x2)-(y0-y2)*(y0-y2));

    s=(a+b+c)/2;

    area_triangle=std::sqrt((s*(s-a)*(s-b)*(s-c)));

    return area_triangle;

}

Upvotes: 0

Views: 9152

Answers (3)

Antonio
Antonio

Reputation: 20266

An alternative formula (with demonstration) can be found here

area = fabs((x0 - x2) * (y1 - y0) - (x0 - x1) * (y2 - y0) ) / 2;

(As a side note, if the formula has to be used to test points collinearity, the absolute value can be removed... But then you might need it anyway, as working with floating points you cannot test equality but against some epsilon value)

Upvotes: 2

Cornstalks
Cornstalks

Reputation: 38218

I haven't made any mistake in the math but it doesn't produce the right result!

If it's not producing the right result, then I think there's a very high chance you made a mistake in the math.

a=std::sqrt((x0-x1)*(x0-x1)-(y0-y1)*(y0-y1));

That - looks suspicious. I'm assuming you're trying to find the distance between (x0, y0) and (x1, y1). If that's the case, you should be adding the two quantities, not subtracting.

I'm not familiar with Heron's formula, but you can use this simpler formula:

area = std::abs(x0 * (y1 - y2) + x1 * (y2 - y0) + x2 * (y0 - y1)) / 2;

Edit: I forgot to mention the abs function for the simplified formula, which was pointed out by Antonio.

Upvotes: 9

mattm
mattm

Reputation: 5949

I think you have a sign error. The values a, b, and c are the triangle sides, right?

a=std::sqrt((x0-x1)*(x0-x1)+(y0-y1)*(y0-y1));
                           ^

Upvotes: 3

Related Questions