1
  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'

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

谢谢

4

1 回答 1

0

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))
于 2020-07-20T08:29:32.220 回答