C++ function calculating the area of a triangle -
i have following function in c++ supposed find area of triangle using heron's formula. haven't made mistake in math doesn't produce right result! looking @ more 3 hours , can't find mistake. 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; }
i haven't made mistake in math doesn't produce right result!
if it's not producing right result, think there's high chance made mistake in math.
a=std::sqrt((x0-x1)*(x0-x1)-(y0-y1)*(y0-y1));
that - looks suspicious. i'm assuming you're trying find distance between (x0, y0) , (x1, y1). if that's case, should adding 2 quantities, not subtracting.
i'm not familiar heron's formula, you can use simpler formula:
area = std::abs(x0 * (y1 - y2) + x1 * (y2 - y0) + x2 * (y0 - y1)) / 2; edit: forgot mention abs function simplified formula, pointed out antonio.
Comments
Post a Comment