# PTA 用虚函数计算各种图形的面积

·  阅读 351

### 输入样例:

``````12.6 3.5 4.5 8.4 2.0 4.5 3.2 4.5 8.4

### 输出样例:

``````578.109

### 代码：

``````#include <iostream>
#include <iomanip>
using namespace std;
#define PI 3.14159f

class Shape
{
public:
virtual float Area() = 0;
};

class Circle:public Shape
{
float r;
public:
Circle(float _r):r(_r) {}
virtual float Area()
{
return PI*r*r;
}

};

class Square:public Shape
{
float t;
public:
Square(float _t):t(_t) {}
virtual float Area()
{
return t*t;
}
};

class Rectangle:public Shape
{
float x, y;
public:
Rectangle(float _x, float _y):x(_x), y(_y) {}
virtual float Area()
{
return x*y;
}
};

class Trapezoid:public Shape
{
float s1, s2, h;
public:
Trapezoid(float _s1, float _s2, float _h):s1(_s1), s2(_s2), h(_h) {}
virtual float Area()
{
return (s1+s2)*h/2;
}
};

class Triangle:public Shape
{
float a, b;
public:
Triangle(float _a, float _b):a(_a), b(_b) {}
virtual float Area()
{
return a*b/2;
}
};

int main()
{
float r, t, x, y, s1, s2, h, a, b;
cin >> r >> t >> x >> y >> s1 >> s2 >> h >> a >> b;
Circle c(r);
Square s(t);
Rectangle re(x, y);
Trapezoid z(s1, s2, h);
Triangle tri(a, b);
Shape *pt[5] = {&c,&s,&re,&z,&tri};
double area = 0.0;
for(int i=0;i<5;i++)
area += pt[i]->Area();
cout << fixed << setprecision(3) << area << endl;
return 0;
}