1

以下是给定边数时计算三角形面积的程序的源代码。

#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,这是错误的。

有谁知道程序不稳定行为的原因?如何纠正?我已将该程序作为 Zip 文件上传

提前致谢。

4

3 回答 3

6

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

s=(a+b+c)/2f;
于 2011-09-29T10:40:16.580 回答
3

假设a,bc中的每一个都是int; 然后a+b+c是一个int
2也是一个int

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

试试(a + b + c) / 2.0

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

于 2011-09-29T10:44:03.013 回答
1
s=((浮点数)a+b+c)/2.0f; 
于 2011-09-29T10:41:17.117 回答