23.试定义TR1(三角形)及其派生类COL(三角柱).

 

 


#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";
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值