【问题标题】:Object Oriented Python Program calculating volume and Surface area of a sphere面向对象的 Python 程序计算球体的体积和表面积
【发布时间】:2015-11-24 23:35:55
【问题描述】:

编写一个 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'

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

【问题讨论】:

  • 通过单击满足您问题的答案中的检查来关闭问题,它将变为绿色。作为对回答您问题的人的“感谢”。

标签: python class python-3.x object


【解决方案1】:

像这样解析输入:

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

它对我有用。

【讨论】:

  • 是的,Python 3 中的input 将输入作为字符串返回,您必须将其显式转换为浮点或整数等数字类型。
【解决方案2】:

什么错误信息

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

意味着您的代码告诉 ** 运算符要操作的东西,即半径和 3,与 ** 运算符不兼容。尤其是把字符串 (str) 提升到幂没有多大意义,不是吗?

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

要对半径的值进行数值运算,您必须将字符串转换为数字。查看内置函数 float(),查看 https://docs.python.org/2/library/functions.html#float,同时查看其他一些内置函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2013-06-12
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多