用面向对象方法编写求5个圆柱体的体积和表面积的C++程序。要求用成员函数实现以下功能: (1)由键盘分别输入5个圆柱体的半径、高; (2)计算圆柱体的体积和表面积; (3)输出5个圆柱体的体积和表面
时间: 2024-05-16 07:13:11 浏览: 24
下面是求5个圆柱体的体积和表面积的 C++程序,使用了面向对象的方法:
```c++
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius;
double height;
public:
void setRadius(double r) {
radius = r;
}
void setHeight(double h) {
height = h;
}
double getVolume() {
return 3.14159 * radius * radius * height;
}
double getSurfaceArea() {
return 2 * 3.14159 * radius * height + 2 * 3.14159 * radius * radius;
}
};
int main() {
Cylinder cylinders[5];
double r, h;
double volume_sum = 0, surface_sum = 0;
for (int i = 0; i < 5; i++) {
cout << "Enter the radius and height of cylinder " << i + 1 << ": ";
cin >> r >> h;
cylinders[i].setRadius(r);
cylinders[i].setHeight(h);
volume_sum += cylinders[i].getVolume();
surface_sum += cylinders[i].getSurfaceArea();
}
cout << "The volume of these 5 cylinders is " << volume_sum << endl;
cout << "The surface area of these 5 cylinders is " << surface_sum << endl;
return 0;
}
```
首先定义了一个 `Cylinder` 类,包含了圆柱体的半径和高,以及计算体积和表面积的成员函数。在 `main` 函数中,声明了一个 `Cylinder` 类型的数组 `cylinders`,用于存储 5 个圆柱体的数据。然后通过循环,从键盘读入 5 个圆柱体的半径和高,分别调用 `setRadius` 和 `setHeight` 设置圆柱体的半径和高,并计算总体积和总表面积。最后输出总体积和总表面积。
需要注意的是,我们在 `Cylinder` 类中定义了 `setRadius`、`setHeight`、`getVolume` 和 `getSurfaceArea` 四个成员函数,这是面向对象编程的一种思想,通过将数据和操作封装在一个类中,方便程序的管理和维护。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)