为什么这个C程序不能用于计算所有输入的三角形区域?

时间:2011-09-29 10:38:39

标签: c debugging turbo-c++

以下是程序的源代码,该程序在给出边时计算三角形的面积。

#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();
}

我使用Turbo C ++编译器3.0版来编译程序。当我将边数分别为10,10和10时,我得到的区域为43.301270,这是正确的。但是当我将值插入1,1和1时,程序将该区域设为0.000000,这显然是错误的。此外,当我插入3,3和3的值时,我得到的区域为2.000000,这是错误的。

有谁知道程序不稳定行为的原因?怎么纠正?我有uploaded the program as a Zip file

提前致谢。

3 个答案:

答案 0 :(得分:6)

您正在使用整数运算来计算s并遭受截断。像这样更改程序以使用浮点运算。

s=(a+b+c)/2f;

答案 1 :(得分:3)

鉴于abc均为int;然后a+b+cint 2也是int

(a + b + c) / 2是整数除法。

尝试(a + b + c) / 2.0

并且更喜欢将double s用于浮点值。

答案 2 :(得分:1)

s=((float)a+b+c)/2.0f;