用c++定义一个圆柱体类Cylinder,类内数据成员有radius(圆柱体底面半径)、height(圆柱体高度),成员函数有构造函数、surface和volume。surface函数实现计算圆柱体的表面积,volume实现计算圆柱体的体积。在main函数中定义Cylinder类的对象c,并调用surface函数计算对象c的表面积,调用volume计算对象c的体积。
时间: 2023-08-21 19:02:37 浏览: 72
好的,这里是实现代码:
```c++
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius;
double height;
public:
Cylinder(double r, double h) {
radius = r;
height = h;
}
double surface() {
return 2 * 3.14 * radius * (radius + height);
}
double volume() {
return 3.14 * radius * radius * height;
}
};
int main() {
Cylinder c(5, 10);
cout << "The surface area of cylinder is: " << c.surface() << endl;
cout << "The volume of cylinder is: " << c.volume() << endl;
return 0;
}
```
运行结果:
```
The surface area of cylinder is: 471
The volume of cylinder is: 785
```
相关问题
用c++编写程序,要求实现建立类cylinder分别表示圆柱体的半径和高度,从键盘输入半径和高度,输出圆柱体体积。
好的,这个问题我可以回答。以下是该程序的代码:
```c++
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius; // 圆柱体底面半径
double height; // 圆柱体高度
public:
Cylinder(double r, double h): radius(r), height(h) {} // 构造函数
double getVolume() { // 计算圆柱体体积
return 3.1415926 * radius * radius * height;
}
};
int main() {
double r, h;
cout << "请输入圆柱体的半径和高度:" << endl;
cin >> r >> h;
Cylinder c(r, h);
cout << "圆柱体的体积为:" << c.getVolume() << endl;
return 0;
}
```
程序中定义了一个 `Cylinder` 类,它有两个私有属性 `radius` 和 `height`,分别表示圆柱体底面半径和高度。构造函数用于对这两个属性进行初始化。类中还定义了一个 `getVolume()` 函数,用于计算圆柱体的体积。在 `main()` 函数中,程序从键盘输入圆柱体的半径和高度,创建一个 `Cylinder` 对象,并输出圆柱体的体积。
注意,程序中使用了常量 `3.1415926` 来表示圆周率。在实际编程中,应该使用 `cmath` 头文件中的 `M_PI` 常量,它可以保证精度。
定义一个圆柱类,用有元函数来求圆柱体的面积和体积
以下是一个简单的圆柱类定义,其中包含了计算圆柱体面积和体积的成员函数:
```c++
#include <iostream>
using namespace std;
class Cylinder {
private:
double radius; // 圆柱底面半径
double height; // 圆柱高度
public:
// 构造函数
Cylinder(double r, double h) {
radius = r;
height = h;
}
// 计算圆柱体积
double volume() const {
return 3.14159 * radius * radius * height;
}
// 计算圆柱侧面积
double lateralArea() const {
return 2 * 3.14159 * radius * height;
}
// 计算圆柱表面积
double surfaceArea() const {
return 2 * 3.14159 * radius * (radius + height);
}
};
int main() {
Cylinder c(3, 5);
cout << "Volume: " << c.volume() << endl;
cout << "Lateral Area: " << c.lateralArea() << endl;
cout << "Surface Area: " << c.surfaceArea() << endl;
return 0;
}
```
在上面的代码中,我们定义了一个 `Cylinder` 类,并在构造函数中初始化圆柱的半径和高度。然后,我们使用三个成员函数 `volume()`、`lateralArea()` 和 `surfaceArea()` 来计算圆柱的体积、侧面积和表面积。注意,在这些函数的定义中,我们使用了 `const` 关键字来表示这些函数不会修改对象的状态。最后,在 `main()` 函数中,我们创建了一个 `Cylinder` 对象并调用了这些成员函数来计算圆柱的面积和体积。