Heron's Formula

From ScriptsPedia

Jump to: navigation, search

Heron's formula (also called Hero's Formula), states that the area (A) of a triangle whose sides have lengths a, b, and c is:

A = \sqrt{s\left(s-a\right)\left(s-b\right)\left(s-c\right)}

where s is the semi perimeter of the triangle:

s=\frac{a+b+c}{2}

See an implementation of this formula in various programming languages:

C++

The Following is an open source implementation of the heron's formula in c++ written by talshk.

#include <cstdlib>
#include <iostream> //import I/O library
#include <math.h> //to support math related functions
 
using namespace std;
 
//Declaring the heron triangle area function
double heron_triangle_area (double a=0, double b=0, double c=0);
 
main()
{
 double a=0, b=0, c=0;
 cout << "Please enter values a,b,c (According to Heron's Formula):\n";
 cin >> a >> b >> c;
 while (heron_triangle_area(a,b,c) == 0)
 {
  cout << "The values of a, b and c must be:\n";
  cout << "1)all positive\n";
  cout << "2)satisfy the triangle inequalities: a+b>c, a+c>b & b+c>a.\n";
  cin >> a >> b >> c;
 }
 cout << "The value is: " << heron_triangle_area (a, b, c); 
 system("PAUSE");
}
/*
heron_triangle_area Function
Parameters:
double a,b,c - triangle sides, must be:
       1) positive
       2) satisfy the triangle inequalities: a+b>c, a+c>b & b+c>a.
returns the triangle area or 0 value (if not a triangle).
*/
double heron_triangle_area (double a, double b, double c)
{
double s;
 if (!(a+b>c) || !(b+c>a) || !(a+c>b) || a<=0 || b<=0 || c<=0)
    return 0;
 else {
      s = ((a+b+c)/2);
      return sqrt(s*(s-a)*(s-b)*(s-c));
      }
}

PHP

The Following script is an open source implementation of the hero's formula written in PHP by talshk.

<?php
/*
heron_triangle_area Function in PHP, Parameters:
double a,b,c - triangle sides, must be:
    1) positive
    2) satisfy the triangle inequalities: a+b>c, a+c>b & b+c>a.
The returns the triangle area or 0 value (if it is not a triangle).*/
function heron_triangle_area ($a, $b, $c)
{
 if (!($a+$b>$c) || !($b+$c>$a) || !($a+$c>$b) || $a<=0 || $b<=0 || $c<=0)
    return 0;
 else {
      $s = (($a + $b + $c)/2);
      return sqrt($s * ($s - $a) * ($s - $b) * ($s - $c));
      }
}
?>

Java

An implementation of the heron's triangles formula in Java, written by talshk

public class heron {
	public static void main ( String args[] )
	{
		double a = 4; // length of side 'A' of the triangle
		double b = 5; // length of side 'B' of the triangle
		double c = 4; // length of side 'C' of the triangle	
		System.out.print(heron_area (a, b, c ));
	}  
 
	public static double heron_area (double a,double b,double c)
	{
		if (!(a+b>c) || !(b+c>a) || !(a+c>b) || a<=0 || b<=0 || c<=0){
			return 0;
		} else {
			double s = 0.5 * (a + b + c);
			double area = Math.sqrt(s*(s-a)*(s-b )*(s-c));
		    return area;  	
	}  
	}
}
Personal tools