What is wrong? Calculate the area.

public class Challenge { public static void main( String[] args ) { double a; a = triangleArea(3, 3, 3); System.out.println("A triangle with sides 3,3,3 has an area of:" + a); a = triangleArea(3, 4, 5); System.out.println("A triangle with sides 3,4,5 has an area of:" + a); a = triangleArea(9, 9, 9); System.out.println("A triangle with sides 9,9,9 has an area of:" + a ); } public static double triangleArea( int a, int b, int c ) { double s=(((a+b+c)/2)*((a+b+c)/2-a)*((a+b+c)/2-b)*((a+b+c)/2-c)); return Math.sqrt(s); } } 
  • and what's wrong? where not so does not compile, incorrectly calculates what? what is not happy? - arg
  • one
    replace int with double. you have 9/2 == 4 - Yura Ivanov
  • @ Ismail Ismailov, If you are given a comprehensive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky

1 answer 1

Divide everywhere by 2.0 , not by 2, and it will work (I think, figure out why yourself).

Hint - read about arithmetic in integers and type conversion (conversion of numeric types) by default.

-

And it would be clearer to write:

  double pp = (a + b + c) / 2.0; // полупериметр return Math.sqrt(pp * (pp - a) * (pp - b) * (pp - c)); // прямо по формуле Герона из вики 
  • Thanks for the help. The initial int in the assignment has tricked me. - Tony Green