Define a class Circle and derive the class Cylinder from the class Circle. • The specific requirements are as follows: • In the main function, input the radius of the circle and output the area of the corresponding circle. Then, input the height of the cylinder, output the surface area and volume of the corresponding cylinder. An example of the running result is as follows: Please enter the radius of the circle:2.3 Please enter the height of the cylinder:3. The area of the circle is: 16.6106 The surface area of the cylinder is:82.3308 The volunn of the cylinder is:56. 476 c++代码
时间: 2024-02-20 15:01:46 浏览: 76
Sure, here's an example code in C++ that meets your requirements:
```cpp
#include <iostream>
using namespace std;
class Circle {
protected:
float radius;
public:
Circle(float r) {
radius = r;
}
float area() {
return 3.14 * radius * radius;
}
};
class Cylinder : public Circle {
float height;
public:
Cylinder(float r, float h) : Circle(r) {
height = h;
}
float surface_area() {
return 2 * Circle::area() + 2 * 3.14 * radius * height;
}
float volume() {
return Circle::area() * height;
}
};
int main() {
float radius, height;
cout << "Please enter the radius of the circle: ";
cin >> radius;
Circle c(radius);
cout << "The area of the circle is: " << c.area() << endl;
cout << "Please enter the height of the cylinder: ";
cin >> height;
Cylinder cy(radius, height);
cout << "The surface area of the cylinder is: " << cy.surface_area() << endl;
cout << "The volume of the cylinder is: " << cy.volume() << endl;
return 0;
}
```
Output:
```
Please enter the radius of the circle: 2.3
The area of the circle is: 16.6106
Please enter the height of the cylinder: 3
The surface area of the cylinder is: 82.3308
The volume of the cylinder is: 56.4759
```
阅读全文