You are on page 1of 3

Hero’s formula

1. #include<iostream.h>
2. #include<conio.h>
3. #include<math.h>
4. void main()
5. {
6. clrscr();
7. float a,b,c,area,S;
8. cout<<"Enter a";
9. cin>>a;
10. cout<<"Enter b";
11. cin>>b;
12. cout<<"enter c";
13. cin>>c;
14. S=((a+b+c)/2);
15. if(S<a || S<b||S<c)
16. {
17. cout<<"Invalid triangle!!!";
18. }
19. else
20. {
21. area=sqrt(S*(S-a)*(S-b)*(S-c));
22. cout<<"The area of triangle is "<<area
;
23. }
24. getch();
25. }
No it looks right to me.

For a valid triangle with sides a, b and c then

a+b>c
a+c>b
b+c>a

are all true i.e the sum of any 2 sides is greater than the 3rd side.

Put another way 3 lines a, b and can not make a valid triangle if any of

a + b <= c
a + c <= b
b + c <= a

are false

time those by 1/2

1/2(a + b) <= 1/2.c


1/2(a + c) <= 1/2.b
1/2(b + c) <= 1/2.a

and it still holds true, add 1/2.c to the first equation, 1/2 b to the second
and 1/2 a to the third

1/2(a + b) + 1/2.c <= 1/2.c + 1/2.c


1/2(a + c) + 1/2.b <= 1/2.b + 1/2.b
1/2(b + c) + 1/2.a <= 1/2.a + 1/2.a

simplify

1/2(a + b + c) <= c
1/2(a + b + c) <= b
1/2(a + b + c) <= a

subsitute 1/2(a + b + c) = S gives and invalid triangle if

S <= c
S <= b
S <= a

which is close to what you have coded but not quite. You code passes as a
valid triangle any three lines where a + b = c (or the other 2
combinations), this is not a triangle as it has no height, the 2 shorter lines
would lay exactly on top of the longer line. Hero's forumla will calculate
the area as 0.

As an example of this try lines 10, 5 and 5.

You can correct your code easily report this invalid case by changing < to
<=

You might also like