繁体   English   中英

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

[英]Object Oriented Python Program calculating volume and Surface area of a sphere

编写一个python程序,计算半径为r的球体,半径为r且高度为h的圆柱体和圆底的半径和高度为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>"))

它为我工作。

什么错误信息

unsupported operand type(s) for ** or pow(): 'str' and 'int'

就是说您的代码告诉**运算符的操作,即radius和3与**运算符不兼容。 特别是将字符串(str)提升为幂没有太大意义,不是吗?

这是因为input()返回一个字符串。

要对radius的值进行数字运算,必须将字符串转换为数字。 查看内置函数float(),请参阅https://docs.python.org/2/library/functions.html#float ,并在那里查看其他一些内置函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM