代码:
#include <iostream>
#include <cmath>
using namespace std;
class Triangle
{
public:
Triangle(double x,double y,double z);
double perimeter();//计算三角形的周长
double area();//计算并返回三角形的面积
void showMessage();
private:
double a,b,c;//三边为私有成员数据
};
Triangle::Triangle(double x,double y,double z)
{
a=x;
b=y;
c=z;
}
double Triangle::perimeter()
{
return a+b+c;
}
double Triangle::area()
{
double p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
void Triangle::showMessage()
{
cout<<"三角形的三边长分别为:"<<a<<' '<<b<<' '<<c<<endl;
cout<<"该三角形的周长为:"<<perimeter()<<",面积为:"<<area()<<endl;
}
int main()
{
Triangle Tri(7,8,9);
Tri.showMessage();
return 0;
}
运行结果: