用c++面向对象程序设计写一段求三角形周长和面积的代码?

尽可能简短
2024-12-26 11:38:52
推荐回答(1个)
回答1:

#include
#include
using namespace std;
enum type
{
area,
circumference,
};
class triangle
{
public:
triangle(float a,float b,float c)
{
this->a=a;
this->b=b;
this->c=c;
valid=((a+b)>c&&(a+c)>b&&(b+c)>a);
}
float getarea() const
{
float t;

if(valid)
{
t=(a+b+c)*0.5;
return sqrt(t*(t-a)*(t-b)*(t-c));
}
else
throw "不能构成三角形,无法求面积";
}
float getcircumference() const
{
if(valid)
return a+b+c;
else
throw "不能构成三角形,无法求周长";
}
static void cal(triangle &tr,enum type t)
{
try
{
switch(t)
{
case area:
cout<<"面积:"< break;
case circumference:
cout<<"周长:"< break;
}
}
catch(const char *ex)
{
cout< }
}
private:
float a,b,c;
bool valid;
};
int main()
{
float a,b,c;

cout<<"请输入三角形的三条边长:";
cin>>a>>b>>c;
triangle t(a,b,c);
triangle::cal(t,area);
triangle::cal(t,circumference);
return 0;
}