21图形的面积

时间限制:1.000S  空间限制:128MB

题目描述

考虑一个简单的图形类层次结构,包括基类 Shape 和两个派生类 Rectangle 和 Circle。每个类都有一个用于计算面积的方法。你的任务是编写一个程序,根据输入数据创建一个图形对象,然后计算并输出其面积。

输入描述

输入包括多行,每行包含一个图形的描述。 描述的第一个单词是图形类型("rectangle"或"circle"),然后是与该图形相关的参数。 对于矩形,参数是宽度和高度,对于圆形,参数是半径。输入以单词"end"结束。

输出描述

对于每个图形描述,输出其类型和面积。使用两位小数点精度输出面积。

输入示例
rectangle 5 3
circle 2
end
输出示例
Rectangle area: 15.00
Circle area: 12.56
提示信息

长方形面积的计算 = 长 * 宽

圆形面积的计算 = 3.14 * 半径 * 半径

代码示例 

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>//用于控制输出格式
using namespace std;
class Shape{
public:
//定义计算面积和获取类型的函数为纯虚函数
    virtual double CalculateArea() const=0;
    virtual string GetType() const =0;
};
 class Rectangle : public Shape {
     public:
     //初始化参数列表
     Rectangle(int width,int height) : width(width),height(height) {}
     //计算长方形面积,将整数转换成浮点数
     double CalculateArea() const override{
         return static_cast<double>(width*height);
     }
     //获取图形的形状
     string GetType() const override {
         return "Rectangle";
     }
//属性:宽度和高度  
private:
     int width;
     int height;
 };
 
 class Circle : public Shape{
     public:
     //初始化参数列表
     Circle(int radius) : radius(radius){}
     //计算图形面积
     double CalculateArea() const  override{
         return 3.14*radius*radius;
     }
     //获取图形的形状
     string GetType() const override{
         return "Circle";
     }
     //属性:半径
private:
int radius;
 };
 int main(){
     //定义一个容器,容纳shape对象
     vector<Shape*> shapes;
     while(true)
     {
         string type;
         //获取输入的type类型
         cin >> type;
         if(type == "end")
         {
             break;
         }
         if(type == "rectangle")
         {
             int width,height;
             cin >> width >>height;
             //新建Rectangle对象
             shapes.push_back(new Rectangle(width,height));
         }
         else if (type == "circle")
         {
             int radius;
             cin >> radius;
             shapes.push_back(new Circle(radius));
         }
     }
     for(const Shape* shape : shapes)
     {
         //shape对象调用同一个方法,有不同的处理逻辑
         cout << shape->GetType() << " area: " << fixed << setprecision(2)<<shape->CalculateArea()<<endl;
     }
     return 0;
 }

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值