#include<iostream>
using namespace std;
#include<math.h>
class RT1
{
private:
double x, y, z;
public:
RT1(double x, double y, double z)
{
this->x = x; this->y = y; this->z = z;
}
virtual double area()
{
double s = (x + y + z) * 0.5;
return sqrt(s * (s - x) * (s - y) * (s - z));
}
double peri()
{
return x + y + z;
}
virtual double volume() = 0;
};
class COL :public RT1
{
private:
double height;
public:
COL(double a1,double b1,double c1,double d1):RT1(a1,b1,c1),height(d1){}
double volume()
{
return RT1::area() * this->height;
}
double area()
{
return RT1::area() * 2 + this->peri() * height;
}
};
int main()
{
double a, b, c, d;
cin >> a >> b >> c >> d;
if (a + b <= c || a + c <= b || b + c <= a)
{
cout << "错误输入" << endl; exit(0);
}
else
{
COL co(a, b, c, d);
RT1* tr = &co;
cout << "三角形周长:\t" << tr->peri() << endl;
cout << "三棱锥表面积:\t" << tr->area() << endl;
cout << "三棱锥体积:\t" << tr->volume() << endl;
}
system("pause");
}
优化:
#include <iostream>
#include <math.h>
using namespace std;
class TR1 {
double x, y, z;
public:
TR1(double x1, double y1, double z1)
{
x = x1; y = y1; z = z1;
}
virtual double area()
{
double s = (x + y + z) / 2;
s = sqrt(s * (s - x) * (s - y) * (s - z));
return s;
}
double print()
{
double s = x + y + z;
return s;
}
};
class COL :public TR1 {
double height;
public:
COL(double x1, double y1, double z1, double h) :TR1(x1, y1, z1)
{
height = h;
}
double volume()
{
double vol = TR1::area();
vol = vol * height;
return vol;
}
double area()
{
double are = TR1::area();
double pri = TR1::print();
are = 2 * are + pri * height;
return are;
}
};
int main()
{
TR1* tr;
double a, b, c, h;
cout << "请输入三角形的底面边长和高:";
cin >> a >> b >> c >> h;
if (a + b > c && a + c > b && b + c > a)
{
COL co(a, b, c, h);
tr = &co;
cout << "三角柱体的体积为:";
cout << co.volume() << '\n';
cout << "三角柱体的表面积为:";
cout << tr->area() << '\n';
}
else
cout << "所输入的三条边不能构成三角形!\n";
}