C++计算圆形、矩形和三角形的面积

题目描述

运用多态编写程序,声明抽象基类Shape,由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea()分别输出以上三者的面积(结果保留两位小数),3个图形的数据在定义对象时给定。

输入

圆的半径 矩形的边长 三角形的底与高

输出

圆的面积

矩形的面积

三角形的面积

注意:每一行后有回车符

样例输入

12.6 4.5 8.4 4.5 8.4

样例输出

area of circle=498.76

area of rectangle=37.80

area of triangle=18.90

代码实现

#include
#include 
#define PI 3.1415926
using namespace std;
class Shape {
    public:
        virtual double printArea()=0;
};
class Circle:public Shape {
    private:
        double r;
    public:
        Circle(double x) {
            r=x;
        }
        virtual double printArea() {
            return PI*r*r;
        }
};
class Rectangle:public Shape {
    private:
        double w,h;
    public:
        Rectangle(double x,double y) {
            w=x,h=y;
        }
        virtual double printArea() {
            return w*h;
        }
};
class Triangle:public Shape {
    private:
        double w,h;
    public:
        Triangle(double x,double y) {
            w=x,h=y;
        }
        virtual double printArea() {
            return w*h/2;
        }
};
double printArea(Shape &x) {
	return x.printArea();
}
int main() {
    double a,b,c,d,e;
    cin>>a>>b>>c>>d>>e;
    Circle cir(a);
    Rectangle rec(b,c);
    Triangle tri(d,e);
    cout<