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 whi开发者_如何学编程ch 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 s
and suffering from truncation. Change your program like this to use floating point arithmetic.
s=(a+b+c)/2f;
Given that each of a
, b
, and c
is an int
; then a+b+c
is an int
.
2
is also an int
.
(a + b + c) / 2
is integer division.
Try (a + b + c) / 2.0
.
And prefer to use double
s for floating point values.
s=((float)a+b+c)/2.0f;
精彩评论