我的主要问题是显示此错误:
TypeError: a float is required
我没有尝试太多,因为我真的不知道自己在做什么,而且对编码等方面还很陌生,所以我希望能就此事提供一些耐心的建议。
from math import sqrt
n = raw_input('Type number here: ')
def square_root(n):
"""Returns the square root of a number."""
square_rooted = sqrt(n)
print "%d square rooted is %d." % (n, square_rooted)
return square_rooted
square_root(n)
我希望能够输入一个数字并显示它的平方根。
最佳答案
代码的一些问题/修复
您需要转换从 raw_input 获得的字符串
要显示 float ,请使用
%f
字符串格式
因此代码将更改为
from math import sqrt
#Convert string obtained from raw_input to float
n = float(raw_input('Type number here: '))
def square_root(n):
"""Returns the square root of a number."""
square_rooted = sqrt(n)
print "%f square rooted is %f." % (n, square_rooted)
return square_rooted
square_root(n)
输出将如下所示
Type number here: 4.5
4.500000 square rooted is 2.121320.
关于python - 为什么我显示 "TypeError: a float is required"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56380520/