c++ 计算图形的面积

该博客介绍了一个C++编程任务,涉及创建一个图形基类Shape,以及Rectangle(长方形)、Circle(圆)和Square(正方形)的派生类。通过这些类,程序可以计算并输出不同图形的面积。示例输入包括圆的半径和不同正方形、长方形的尺寸,输出为对应图形的面积。
摘要由CSDN通过智能技术生成

Problem Description
定义一个图形基类Shape,在此基础上派生出长方形Rectangle和圆Circle,
使用Rectangle类派生正方形类Square。计算图形的面积。
请完善下面的程序。
//你的代码将被嵌在这里
int main()
{
Shape* ps;
Rectangle* pr;

double r;
cin >> r;
ps = new Circle(r);
cout << "The area of the Circle is " << ps->getArea() << endl;
delete ps;

double l,w;
cin >> l>>w;
ps = new Rectangle(l, w);
cout << "The area of the Rectagle is " << ps->getArea() << endl;
delete ps;

double s1;
cin >> s1;
ps = new Square(s1);
cout << "The area of the Square is " << ps->getArea() << endl;
delete ps;

double s2;
cin >> s2;
pr = new Square(s2);
cout << "The area of the Square is " << pr->getArea() << endl;
delete pr;

return 0;

}

Input Description
第1个数是圆的半径
第2、3个数是长方形的长和宽
第4个数是一个正方形的边长
第5个数是另一个正方形的边长
Sample Input
1 2 3 4 5
Sample Output
The area of the Circle is 3.14
The area of the Rectagle is 6
The area of the Square is 16
The area of the Square is 25

#include <iostream>
using namespace std;
constexpr double PI = 3.14;

class Shape
{
   
public:
    Shape(){
   }//基类要有构造函数
    virtual double getArea() = 0;//纯虚函数
};

class Rectangle:public Shape
{
   
public:
    double x, y;
    Rectangle(double a, double b)
    {
   
        x = a;
        y = b;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值