Skip to main content
 首页 » 编程设计

python之面向对象的 Python 程序计算球体的体积和表面积

2025年05月04日15webabcd

编写一个 Python 程序,计算半径为 r 的球体、半径为 r 且高度为 h 的圆形底面的圆柱体以及半径为 r 且高度为 h 的圆形底面的圆锥体的体积和表面积。将它们放入几何模块中。然后编写一个程序,提示用户输入 r 和 h 的值,调用六个函数,并打印结果。

这是我的代码

from math import sqrt 
from math import pi 
 
 
# FUNCTIONS 
def sphere_volume(radius): 
    return 4/3 * pi * (radius ** 3) 
 
 
def sphere_surface(radius): 
    return 4 * pi * radius ** 2 
 
 
def cylinder_volume(radius, height): 
    return pi * radius ** 2 
 
 
def cylinder_surface(radius, height): 
    return pi * radius ** 2 * 2 * pi * radius * height 
 
 
def cone_volume(radius, height): 
    return 1/3 * pi * radius ** 2 * height 
 
 
def cone_surface(radius, height): 
    return pi * radius ** 2 + pi * radius * sqrt(height ** 2 + radius ** 2) 
 
 
# main 
def main(): 
    radius = input("Radius>") 
    height = input("Height>") 
 
    print("Sphere volume: %d" %(sphere_volume(radius))) 
    print("Sphere surface: %d" %(sphere_surface(radius))) 
    print("Cylinder volume: %d" %(cylinder_volume(radius, height))) 
    print("Cylinder surface area: %d" %(cylinder_surface(radius, height))) 
    print("Cone volume: %d" %(cone_volume(radius, height))) 
    print("Cone surface: %d" %(cone_surface(radius, height))) 
 
 
# PROGRAM RUN 
if __name__ == "__main__": 
    main() 

我遇到了一个错误

 return 4/3 * pi * (radius ** 3) 
 
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' 

有人可以帮我解决我做错了什么吗?

请您参考如下方法:

像这样解析输入:

# main 
def main(): 
    radius = float(input("Radius>")) 
    height = float(input("Height>")) 

它对我有用。