怎么用编程编写一个圆柱

时间:2025-01-28 04:39:39 网络游戏

要用编程编写一个圆柱,你可以选择不同的编程语言来实现。以下是几种常见编程语言的示例代码:

1. Java

```java

public class Circle {

private double radius;

public Circle(double radius) {

this.radius = radius;

}

public double getArea() {

return Math.PI * radius * radius;

}

public double getCircumference() {

return 2 * Math.PI * radius;

}

}

public class Cylinder extends Circle {

private double height;

public Cylinder(double radius, double height) {

super(radius);

this.height = height;

}

public double getVolume() {

return getArea() * height;

}

public double getSurfaceArea() {

return 2 * getArea() + 2 * Math.PI * radius * height;

}

}

public class Main {

public static void main(String[] args) {

Cylinder cylinder = new Cylinder(5, 10);

System.out.println("圆柱的体积为: " + cylinder.getVolume());

System.out.println("圆柱的表面积为: " + cylinder.getSurfaceArea());

}

}

```

2. C++

```cpp

include

include

class Circle {

private:

double radius;

public:

Circle(double radius) : radius(radius) {}

double getArea() {

return M_PI * radius * radius;

}

double getCircumference() {

return 2 * M_PI * radius;

}

};

class Cylinder : public Circle {

private:

double height;

public:

Cylinder(double radius, double height) : Circle(radius), height(height) {}

double getVolume() {

return getArea() * height;

}

double getSurfaceArea() {

return 2 * getArea() + 2 * M_PI * radius * height;

}

};

int main() {

Cylinder cylinder(5, 10);

std::cout << "圆柱的体积为: " << cylinder.getVolume() << std::endl;

std::cout << "圆柱的表面积为: " << cylinder.getSurfaceArea() << std::endl;

return 0;

}

```

3. Python

```python

import math

class Circle:

def __init__(self, radius):

self.radius = radius

def get_area(self):

return math.pi * self.radius 2

def get_circumference(self):

return 2 * math.pi * self.radius

class Cylinder(Circle):

def __init__(self, radius, height):

super().__init__(radius)

self.height = height

def get_volume(self):

return self.get_area() * self.height

def get_surface_area(self):

return 2 * self.get_area() + 2 * math.pi * self.radius * self.height

示例

cylinder = Cylinder(5, 10)

print("圆柱的体积为:", cylinder.get_volume())

print("圆柱的表面积为:", cylinder.get_surface_area())

```

4. C语言

```c

include

include

define PI 3.14159

double calculate_volume(double radius, double height) {

return PI * radius * radius * height;

}

double calculate_surface_area(double radius, double height) {

return 2 * PI * radius * (radius + height);

}

int main() {

double radius, height;

printf("请输入圆柱体的底面半径和高度: ");

scanf("%lf %lf", &radius, &height);

double volume = calculate_volume(radius, height);

double surface_area = calculate_surface_area(radius, height);

printf("圆柱体的体积为: %.2lf\n", volume);

printf("圆柱体的表面积为: %.2lf\n", surface_area);

return 0;

}

```

这些示例代码展示了如何使用不同编程语言