创建类MyMath,计算圆的周长和面积以及球的表面积和体积,并编写测试代码,结果均保留两位小数(提示:编写四个类方法)。 运行效果示例: 请输入半径:5 圆的周长 = 31.42 圆的面积 = 78.54 球的表面积 = 314.16 球的体积 = 523.60
时间: 2024-03-09 17:47:21 浏览: 25
以下是实现了 MyMath 类的 Python 代码:
```python
import math
class MyMath:
@classmethod
def circle_circumference(cls, r):
"""计算圆的周长"""
return round(2 * math.pi * r, 2)
@classmethod
def circle_area(cls, r):
"""计算圆的面积"""
return round(math.pi * r ** 2, 2)
@classmethod
def sphere_surface_area(cls, r):
"""计算球的表面积"""
return round(4 * math.pi * r ** 2, 2)
@classmethod
def sphere_volume(cls, r):
"""计算球的体积"""
return round(4 / 3 * math.pi * r ** 3, 2)
```
可以通过类方法 `circle_circumference`、`circle_area`、`sphere_surface_area` 和 `sphere_volume` 计算圆的周长和面积以及球的表面积和体积。每个方法都接受圆的半径参数 `r`,并返回计算结果,结果使用 `round()` 函数保留两位小数。
以下是测试代码示例:
```python
r = float(input("请输入半径:"))
print("圆的周长 =", MyMath.circle_circumference(r))
print("圆的面积 =", MyMath.circle_area(r))
print("球的表面积 =", MyMath.sphere_surface_area(r))
print("球的体积 =", MyMath.sphere_volume(r))
```
运行效果示例:
```
请输入半径:5
圆的周长 = 31.42
圆的面积 = 78.54
球的表面积 = 314.16
球的体积 = 523.6
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)