用c++编写程序,调用函数求一个圆柱体的体积
时间: 2023-06-08 17:04:17 浏览: 106
好的,这是一个数学问题,我可以回答。圆柱体的体积公式为V=πr²h,其中π取3.14左右,r为圆柱体的底面半径,h为圆柱体的高。因此,您可以编写一个程序,输入r和h的值,通过调用函数计算并输出圆柱体的体积。
相关问题
c++使用虚函数求球体和圆柱体的体积和表面积
以下是使用虚函数求球体和圆柱体的体积和表面积的C++代码示例:
```
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double getVolume() = 0;
virtual double getSurfaceArea() = 0;
};
class Sphere : public Shape {
private:
double radius;
public:
Sphere(double r) {
radius = r;
}
double getVolume() {
return (4.0/3.0) * M_PI * pow(radius, 3);
}
double getSurfaceArea() {
return 4 * M_PI * pow(radius, 2);
}
};
class Cylinder : public Shape {
private:
double radius;
double height;
public:
Cylinder(double r, double h) {
radius = r;
height = h;
}
double getVolume() {
return M_PI * pow(radius, 2) * height;
}
double getSurfaceArea() {
return 2 * M_PI * radius * (radius + height);
}
};
int main() {
Shape* shape;
Sphere sphere(2.0);
Cylinder cylinder(2.0, 5.0);
shape = &sphere;
cout << "Sphere Volume: " << shape->getVolume() << endl;
cout << "Sphere Surface Area: " << shape->getSurfaceArea() << endl;
shape = &cylinder;
cout << "Cylinder Volume: " << shape->getVolume() << endl;
cout << "Cylinder Surface Area: " << shape->getSurfaceArea() << endl;
return 0;
}
```
在上面的代码中,我们定义了一个抽象基类`Shape`,包含两个纯虚函数`getVolume`和`getSurfaceArea`。然后,我们定义了两个派生类`Sphere`和`Cylinder`,分别表示球体和圆柱体。这两个派生类继承了`Shape`类,并实现了`getVolume`和`getSurfaceArea`函数。
在`main`函数中,我们首先创建了一个`Sphere`对象和一个`Cylinder`对象,并将它们的地址分别赋给一个`Shape`指针变量`shape`。然后,我们通过`shape`指针调用了`getVolume`和`getSurfaceArea`函数,分别输出了球体和圆柱体的体积和表面积。
需要注意的是,我们在`Shape`类中将`getVolume`和`getSurfaceArea`函数声明为纯虚函数,这意味着我们不能直接创建`Shape`对象,而只能通过派生类来创建对象。这种技术称为抽象类,它可以帮助我们实现多态性,即在运行时根据对象的实际类型来调用相应的函数。
使用虚函数编写程序,求球体和圆柱体的面积
以下是使用虚函数编写求球体和圆柱体面积的程序:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 定义基类Shape
class Shape {
public:
virtual double getArea() = 0; // 声明虚函数getArea
};
// 定义派生类Sphere,表示球体
class Sphere : public Shape {
private:
double radius; // 球体半径
public:
Sphere(double r) : radius(r) {} // 构造函数
double getArea() { return 4 * M_PI * radius * radius; } // 实现虚函数getArea,计算球体面积
};
// 定义派生类Cylinder,表示圆柱体
class Cylinder : public Shape {
private:
double radius; // 圆柱体底面半径
double height; // 圆柱体高
public:
Cylinder(double r, double h) : radius(r), height(h) {} // 构造函数
double getArea() { return 2 * M_PI * radius * height + 2 * M_PI * radius * radius; } // 实现虚函数getArea,计算圆柱体面积
};
int main() {
Sphere s(5); // 创建球体对象
Cylinder c(3, 10); // 创建圆柱体对象
// 分别调用虚函数getArea计算面积并输出
cout << "球体面积:" << s.getArea() << endl;
cout << "圆柱体面积:" << c.getArea() << endl;
return 0;
}
```
输出结果为:
```
球体面积:314.159
圆柱体面积:188.496
```