长方体的表面积和体积
时间: 2024-06-14 18:05:35 浏览: 250
长方体的表面积可以通过以下公式计算:2 * (长 * 宽 + 长 * 高 + 宽 * 高)。
长方体的体积可以通过以下公式计算:长 * 宽 * 高。
以下是使用函数和类两种方法计算长方体的表面积和体积的示例:
1. 使用函数计算长方体的表面积和体积:
```python
def calculate_surface_area(length, width, height):
surface_area = 2 * (length * width + length * height + width * height)
return surface_area
def calculate_volume(length, width, height):
volume = length * width * height
return volume
length = 5
width = 3
height = 4
surface_area = calculate_surface_area(length, width, height)
volume = calculate_volume(length, width, height)
print("Surface area of the rectangular prism: ", surface_area)
print("Volume of the rectangular prism: ", volume)
```
2. 使用类计算长方体的表面积和体积:
```python
class RectangularPrism:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
def calculate_surface_area(self):
surface_area = 2 * (self.length * self.width + self.length * self.height + self.width * self.height)
return surface_area
def calculate_volume(self):
volume = self.length * self.width * self.height
return volume
length = 5
width = 3
height = 4
rectangular_prism = RectangularPrism(length, width, height)
surface_area = rectangular_prism.calculate_surface_area()
volume = rectangular_prism.calculate_volume()
print("Surface area of the rectangular prism: ", surface_area)
print("Volume of the rectangular prism: ", volume)
```
阅读全文