Problem:
Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.
import java.util.Scanner;
public class AreaOfTriangle
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
final double NUM_ONE = 0.5;
int a, b, c;
double s, area;
System.out.print("Enter side a: ");
a = scan.nextInt();
System.out.print("Enter side b: ");
b = scan.nextInt();
System.out.print("Enter side c: ");
c = scan.nextInt();
s = NUM_ONE * (a + b + c);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("\nThe area of the triangle = " + area);
}
}
The formula is correct, but s*(s-a)*(s-b)*(s-c)
could end up being very slightly negative depending on the inputs (due to floating point imprecision). You should test this prior to taking the sqrt
, and return zero in that instance.
Math.sqrt
on a negative number will return NaN
.