定义抽象基类CShape,由它派生出3个派生类:CCircle(圆形)、CRectangle(矩形)、CTriangle(三角形),分别计算这几种图形的周长和面积。

#include <iostream>

#include <math.h>

#define PI 3.14

using namespace std;

class CShape

{

    public:

        virtual double perimeter()

        const = 0;

        virtual double area()

        const = 0;

};

// 圆

class CCircle : public CShape {

private:

    double radius;

public:

    CCircle(double r) : radius(r) {}

    double perimeter() const {

        return 2 * PI * radius;

    }

    double area() const {

        return PI * radius * radius;

    }

};

// 矩形

class CRectangle : public CShape {

private:

    double length;

    double width;

public:

    CRectangle(double l, double w) : length(l), width(w) {}

    double perimeter() const {

        return 2 * (length + width);

    }

    double area() const {

        return length * width;

    }

};

// 三角形

class CTriangle : public CShape {

private:

    double x;

    double y;

    double z;

public:

    CTriangle(double a, double b, double c) : x(a), y(b), z(c) {}

    double perimeter() const {

        return x + y + z;

    }

    double area() const {

        double s = (x + y + z) / 2;

        return sqrt(s * (s - x) * (s - y) * (s - z));

    }

};

int main() {

    int m;

    double length, width, radius, a, b, c;

    CShape* shape = nullptr;

    cout << "输入计算图形的类型(1圆 2矩形 3三角形)" << endl;

    cin >> m;

    switch (m) {

    case 1:

        cout << "请输入圆形的半径:";

        cin >> radius;

        shape = new CCircle(radius);

        cout << "圆形的周长为:" << shape->perimeter() << endl;

        cout << "圆形的面积为:" << shape->area() << endl;

        break;

    case 2:

        cout << "请输入矩形的长和宽:";

        cin >> length >> width;

        shape = new CRectangle(length, width);

        cout << "矩形的周长为:" << shape->perimeter() << endl;

        cout << "矩形的面积为:" << shape->area() << endl;

        break;

    case 3:

        cout << "请输入三角形的三条边长:";

        cin >> a >> b >> c;

        if (a + b > c && a + c > b && b + c > a)

        {

            shape = new CTriangle(a, b, c);

            cout << "三角形的周长为:" << shape->perimeter() << endl;

            cout << "三角形的面积为:" << shape->area() << endl;

        }

        else

            cout << "这三边无法组成三角形"<< endl ;

        break;

    default:

        cout << "无此选项" << endl;

        break;

    }

    return 0;

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值