问题描述】画面设计公司,设计彩色图形,不同形状、不同颜色图形,需要统计红,蓝两种颜色的使用面积,以便购买绘制涂料。请设计图形类Figure,有color属性,求面积函数,返回颜色函数;定义子类矩形类,定义子类椭圆类。请用纯虚函数,多态实现。其中,PI用3.14,其他数值型用double,最后输出保留2位小数。 【输入形式】椭圆的数目 椭圆的短半轴,长半轴,颜色 .... 矩形的数目 矩形的长,宽,颜色 .... 【输出形式】每种颜色的面积 【样例输入】 2 3,4,r 5,6,b 3 6,7,r 8,9,r 4,7,b 【样例输出】 red area:151.68 blue area:122.20 c++
时间: 2023-11-28 14:51:15 浏览: 62
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const double PI = 3.14;
class Figure {
protected:
string color;
public:
Figure(string c) : color(c) {}
virtual double getArea() = 0;
string getColor() { return color; }
};
class Rectangle : public Figure {
private:
double length;
double width;
public:
Rectangle(double l, double w, string c) : Figure(c), length(l), width(w) {}
virtual double getArea() { return length * width; }
};
class Ellipse : public Figure {
private:
double shortRadius;
double longRadius;
public:
Ellipse(double sr, double lr, string c) : Figure(c), shortRadius(sr), longRadius(lr) {}
virtual double getArea() { return PI * shortRadius * longRadius; }
};
int main() {
int n;
vector<Figure*> figures;
double r, R, l, w;
string c;
double redArea = 0.0, blueArea = 0.0;
// 输入椭圆
cin >> n;
for (int i = 0; i < n; i++) {
cin >> r >> R >> c;
figures.push_back(new Ellipse(r, R, c));
}
// 输入矩形
cin >> n;
for (int i = 0; i < n; i++) {
cin >> l >> w >> c;
figures.push_back(new Rectangle(l, w, c));
}
// 统计面积
for (int i = 0; i < figures.size(); i++) {
if (figures[i]->getColor() == "r") {
redArea += figures[i]->getArea();
}
else if (figures[i]->getColor() == "b") {
blueArea += figures[i]->getArea();
}
}
// 输出结果
cout << "red area:" << fixed << setprecision(2) << redArea << " ";
cout << "blue area:" << fixed << setprecision(2) << blueArea << endl;
// 释放内存
for (int i = 0; i < figures.size(); i++) {
delete figures[i];
}
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)