酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

c++声明基类shape,由它派生出三个类,圆形circle,矩形rectangle,三角形triangle,用一个函数输出三个面积。 输入格式: 在一行中依次输入5个数,圆的半径,长方形的高和宽,三角形的高和底,中间用空格分隔 输出格式: 圆的面积,长方形的面积,三角形的面积,小数点后保留2位有效数字,每个面积占一行

```cpp #include <iostream> #include <iomanip> // 基类 Shape class Shape { public: virtual double getArea() = 0; }; // 圆形类 Circle 派生自 Shape class Circle : public Shape { private: double radius; public: Circle(double r) { radius = r; } double getArea() { return 3.14159 * radius * radius; } }; // 矩形类 Rectangle 派生自 Shape class Rectangle : public Shape { private: double height, width; public: Rectangle(double h, double w) { height = h; width = w; } double getArea() { return height * width; } }; // 三角形类 Triangle 派生自 Shape class Triangle : public Shape { private: double height, base; public: Triangle(double h, double b) { height = h; base = b; } double getArea() { return 0.5 * height * base; } }; // 计算并输出三个图形面积的函数 void printAreas(double radius, double heightRect, double widthRect, double heightTri, double baseTri) { Circle circle(radius); Rectangle rectangle(heightRect, widthRect); Triangle triangle(heightTri, baseTri); std::cout << std::fixed << std::setprecision(2); std::cout << circle.getArea() << std::endl; std::cout << rectangle.getArea() << std::endl; std::cout << triangle.getArea() << std::endl; } int main() { double radius, heightRect, widthRect, heightTri, baseTri; std::cin >> radius >> heightRect >> widthRect >> heightTri >> baseTri; printAreas(radius, heightRect, widthRect, heightTri, baseTri); return 0; } ``` 需要注意的逻辑点: 1. 输入数据的合法性检查,比如半径不能为负数。 2. 浮点数的精度控制,确保输出的面积符合要求。 3. 对于派生类的对象创建和使用,要确保正确调用了虚函数来获取面积。 [2024-12-01 22:26:12 | AI写代码神器 | 500点数解答]

相关提问