The following is the source code of a program which calculates the area of a triangle when the sides are given.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
float s,area;
clrscr();
printf("Enter the lengths of the sides of the triangle:\n");
scanf("%d%d%d",&a,&b,&c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area=%f",area);
getch();
}
I used the Turbo C++ compiler Version 3.0 to compile the program. When I give the sides as 10, 10 and 10, I get the area as 43.301270 which is correct. But when I plug the values as 1,1 and 1, the program gives the area as 0.000000 which is obviously wrong. Further, when I plug in the values as 3,3 and 3 I get the area as 2.000000 which is wrong.
Does anyone know the reason for the program’s erratic behavior? How can it be corrected? I have uploaded the program as a Zip file.
Thanks in advance.
You are using integer arithmetic for the calculation of
sand suffering from truncation. Change your program like this to use floating point arithmetic.