时间限制: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;
}