题目描述
定义一个形状类shape,将它作为基类派生出类:circle(圆)、triangle(三角形)和rectangle(长方形)。
分别定义这些派生类并且定一个虚函数来计算各个形状的面积。
输入
包含多组测试例, 每组数据的占1行,分别是圆的半径、三角形的三条边长和长方形的两条边长。
输出
圆、三角形、长方形的面积(保留3位小数)。
样例输入 Copy
10 3 4 5 6 8
15.5 5.8 12.5 13.4 10.56 12.54
样例输出 Copy
314.000
6.000
48.000
754.385
36.158
132.422
提示
#define PI 3.14
# include <iostream>
using namespace std;
# include <cmath>
# include <iomanip>
class shape
{
public:
virtual void area(){}
};
class circle :public shape
{
public:
circle(double r_): r(r_){}
void area()
{
cout << r * 3.14 * r << endl;
}
private:
double r;
};
class trangle :public shape
{
public:
trangle(double x_, double y_, double m_):x(x_), y(y_), m(m_){}
void area()
{
double s = (x + y + m) / 2;
cout << sqrt(s * (s - x) * (s - y) * (s - m)) << endl;
}
private:
double x, y, m;
};
class rectangle :public shape
{
public:
rectangle(double x_, double y_):x(x_), y(y_){}
void area()
{
cout << x*y << endl;
}
private:
double x, y;
};
int main()
{
shape* p;
double a, b, cc, d, e, f;
while (cin >> a >> b >> cc >> d >> e >> f)
{
cout << fixed << setprecision(3);
circle c(a);
p = &c;
p->area();
trangle t(b, cc, d);
p = &t;
p->area();
rectangle r(e, f);
p = &r;
p->area();
}
return 0;
}