头文件:
class Triangle{
private:
double a,b,c;
public:
inline void setA(double x){a=x;}
inline void setB(double y){b=y;}
inline void setC(double z){c=z;}
inline double getA(){return a;}
inline double getB(){return b;}
inline double getC(){return c;}
bool isTriangle();
double perimeter(void);
double area(void);
};
类定义文件:
#include "triangle.h"
#include<Cmath>
using namespace std;
double Triangle::perimeter(void)//计算三角形的周长
{
return a+b+c;
}
double Triangle::area(void)//计算并返回三角形的面积
{
double s=(a+b+c)/2;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
bool Triangle::isTriangle()
{
if((a+b)>c&&(a-b)<c)
return true;
else
return false;
}
主文件:
#include<iostream>
#include "triangle.h"
using namespace std;
int main(){
Triangle tril;//定义三角形的一个实例(类)
double x,y,z;
cout<<"请输入三角形的三边;";
cin>>x>>y>>z;
tril.setA(x);
tril.setB(y);
tril.setC(z);
if(tril.isTriangle()){
cout<<"三条边为:"<<tril.getA()<<','<<tril.getB()<<','<<tril.getC()<<endl;
cout<<"三角形的周长为:"<<tril.perimeter()<<'\t'<<"面积为:"<<tril.area()<<endl;
}
else
cout<<"不能构成三角形!"<<endl;
system("pause");
return 0;
}
运行结果: