西加加:7-2 用虚函数计算各种图形的面积

    技术2025-04-16  12

    定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,输出它们的面积和。要求用基类指针数组,每一个数组元素指向一个派生类的对象。PI=3.14159f,单精度浮点数计算。

    输入格式:

    输入在一行中,给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。

    输出格式:

    输出所有图形的面积和,小数点后保留3位有效数字。

    输入样例:

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

     

    Processed: 0.010, SQL: 9