Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

Using heron's formula to calculate the area of a triangle

russell lloyd
Greenhorn
Posts: 18
For some reason which passes understanding my teacher has asked that we Create a program that will calculate the area of a formula using Heron's formula which is
area = squareroot(S * (S - A) * (S - B) * (S - C))
Where S = the perimeter of the triangle divided by 2.
and Where A,B,C are the lengths of the three sides.
Looking through my textbook and the material that we have covered in class the only way i can figure out to write that line is

but this always gives me an area of zero so i'm pretty sure that this isn't the best way to go about writing the algorithm. I personally think that it's getting messed up in the squareroot part but if someone could please help me with this algorithm that would be great thanks a lot.

David Harkness
Ranch Hand
Posts: 1646
Other than using Math.sqrt(x) instead of Math.pow(x, 0.5), my only suggestion is to post more of your code. I just coded up a solution using your formula and it worked. Well, I didn't verify the areas, but it prints zero only when I expect it (a + b == c, which is an empty triangle).

So to recap.
• Use Math.sqrt()
• Post more of your code
• Post output from a run that demonstrates failure, preferably with printlns of your sides and permeter (any intermediate calculations)

•
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34839
369
Russell,
Welcome to JavaRanch!

This looks correct to me. I suggest breaking up the expression so you can see where things are going wrong. For example:

That way you can print each of the variables (or step through them if using a debugger) and see where things aren't what you expect.

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
My guess is that Russell is using int variables instead of doubles, and the resulting integer math is causing fractions to be rounded to 0.

russell lloyd
Greenhorn
Posts: 18
thank you guys for all of this as it turns out my code is right but i wasn't thinking beacause my test that i was using was sides = 1,2,3 which isn't a triangle(boy i felt stupid) but thank all of you for your suggestions. Sorry it took so long to thank you guys I fell asleep last night

David Harkness
Ranch Hand
Posts: 1646
Yes, I did the same thing as well: 1 1 2 == 0 ... "What?! Mine doesn't work either."