派生类计算面积

题目:定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea( )函数计算对象的面积,再使用Rectangle类创建一个派生类Square。在主函数中测试Rectangle、Circle和Square这三个类。

输入格式:

Rectangle的长和宽、Circle的半径、Square的边长

输出格式:

Rectangle、Circle和Square对应的面积。四舍五入到整数

输入样例 :

3 7 6 4
2.1 3.5 10.3 4.5

输出样例 :

21 113 16
7 333 20
#include <iostream>
#include<cmath>
using namespace std;
class Shape {
public:
    double len, wid, rou, bi;
    double getArea1(double len,double wid){ return len * wid;};//矩形算面积
    double getArea2(double rou){ return 3.14*rou*rou;};//圆形算面积
    double getArea3(double bi){return bi*bi;};//正方形算面积
};

class Rectangle :public Shape {
private:
    double len, wid;
public:
    Rectangle(double l, double w) :len(l), wid(w) {}
    double getArea1() { return len * wid; }
};

class Circle :public Shape {
private:
    double rou;
public:
    Circle(double r) :rou(r) {}
    double getArea2() { return 3.14 * rou * rou; }
};

class Square :public Shape {
private:
    double bi;
public:
    Square(double b) :bi(b) {}
    double getArea3() { return bi * bi; }
};

int main()
{
    double length, width, rough, bian;
    while (cin >> length >> width >> rough >> bian) {
        Shape* ps;
        ps = new Rectangle(length, width);
        Shape* pr;
        pr = new Circle(rough);
        Shape* pb;
        pb = new Square(bian);
        int a = round(ps->getArea1(length,width ));//利用数学库中的round函数可以对小数点后一位四舍五入
        int b = round(pr->getArea2( rough));
        int c = round(pb->getArea3(bian ));
        cout << a << " " << b << " " << c << endl;

    }
}

其中有个没有符合题目要求的地方不知道你发现了没有~ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值