【问题标题】:Unsupported operand type from a function函数中不支持的操作数类型
【发布时间】:2020-11-09 11:09:10
【问题描述】:
  1. 编写一个 Python 程序,该程序接受用户提供的圆的半径并计算面积。转到编辑器 样本输出: r = 1.1 面积 = 3.8013271108436504

我的代码:

def rad_to_area(rad):
    from math import pi
    area = pi * (rad**2)
    return area
radius = input('Enter radius of circle: ')
print('The area of the circle is', rad_to_area(radius))

错误:

Traceback (most recent call last):
  File "/tmp/sessions/167965d8c6c342dd/main.py", line 6, in <module>
    print('The area of the circle is', rad_to_area(radius))
  File "/tmp/sessions/167965d8c6c342dd/main.py", line 3, in rad_to_area
    area = pi * (rad**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

谁能解释一下我做错了什么?

谢谢

【问题讨论】:

    标签: function types operands


    【解决方案1】:

    input 方法是一个字符串,要对半径进行幂运算,您需要先将其转换为浮点数。

    def rad_to_area(rad):
        from math import pi
        area = pi * (rad**2)
        return area
    radius = float(input('Enter radius of circle: ')) #Casting as a float here
    print('The area of the circle is', rad_to_area(radius))
    

    【讨论】:

    • 感谢 Edeki。你花了多长时间才变得精通?现在开始怀疑
    • 如果您愿意,可以查看我的个人资料并通过其中的任何链接向我发送消息,以便当面交谈。
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 2017-07-15
    • 2020-02-29
    • 2011-03-08
    相关资源
    最近更新 更多