#include
#include
using namespace std;
class Triangle
{
public:
Triangle(float a,float b,float c,float d,float e,float f);
void GetArea();
void GetPerimeter();
void panding();
void Show();
void Set(float a,float b,float c,float d,float e,float f);
private:
float x1; float y1;
float x2; float y2;
float x3; float y3;
};
Triangle::Triangle(float a,float b,float c,float d,float e,float f)
{
cout<<"constructing..."<<endl;
x1=a; y1=b;
x2=c; y2=d;
x3=e; y3=f;
}
void Triangle::GetArea()
{
float area,h,AB,AC,BC;
AB=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
AC=sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
BC=sqrt((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2));
if(AB+AC>BC||AB+BC>AC||AC+BC>AB)
{
cout<<"可构成三角形"<<endl;
h=(1/2)*(AB+AC+BC);
area=sqrt(h*(h-AB)*(h-AB)*(h-BC));
cout<<"面积="<<area<<endl;
}
else
cout<<"不能构成三角形,无法计算面积"<<endl;
}
void Triangle::GetPerimeter()
{
float per,AB,AC,BC;
AB=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
AC=sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
BC=sqrt((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2));
if(AB+AC>BC||AB+BC>AC||AC+BC>AB)
{
per=AB+AC+BC;
cout<<"周长="<<per<<endl;
}
else
cout<<"不能构成三角形,无法计算周长"<<endl;
}
void Triangle::Set(float a,float b,float c,float d,float e,float f)
{
x1=a; y1=b;
x2=c; y2=d;
x3=e; y3=f;
}
void Triangle::Show()
{
cout<<"坐标为:"< cout }
void main()
{
float a1,b1,c1,d1,e1,f1;
cin>>a1>>b1>>c1>>d1>>e1>>f1;
Triangle Triangle1(a1,b1,c1,d1,e1,f1);
cout<<"Triangle 1"< Triangle1.Show();
Triangle1.GetArea();
Triangle1.GetPerimeter();
float a2,b2,c2,d2,e2,f2;
cin>>a2>>b2>>c2>>d2>>e2>>f2;
Triangle1.Set(a2,b2,c2,d2,e2,f2);
cout<<"Triangle 2"<<endl;
Triangle1.Show();
Triangle1.GetArea();
Triangle1.GetPerimeter();
}
程序可以运行,但是在GetArea()中,为什么输出的面积结果为0,已经是float型了,但输出结果都是0,这个问题怎么解决?
将h=(1/2) 中的1/2改为0.5, 因为1/2的结果是0,计算机是按照整形处理这个结果的
area=sqrt(h*(h-AB)*(h-AB)*(h-BC));
写错了
GetArea函数体改成
float area,h,AB,AC,BC;
AB=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
AC=sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
BC=sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
if(AB+AC>BC||AB+BC>AC||AC+BC>AB)
{
cout<<"可构成三角形\n";
h=(AB+AC+BC)/2;
area=sqrt(h*(h-AB)*(h-AC)*(h-BC));
cout<<"面积="<<area<<endl;
}
else
cout<<"不能构成三角形,无法计算面积";
其实就是h=(1/2)*(AB+AC+BC);和area=sqrt(h*(h-AB)*(h-AB)*(h-BC));写错了,1/2是两个整型数相除,结果自动转化为整数,即0,再与后面的式子相乘,自然导致最后的结果也为0。如果直接除以2,2这个整型数就会转为float型。