2

我的主要问题是显示此错误:

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)

我希望能够输入一个数字并显示它的平方根。

4

4 回答 4

2

您的代码的一些问题/修复

所以代码将更改为

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.
于 2019-05-30T14:46:23.090 回答
2

更改代码以将字符串转换为浮点数。将结果输入为字符串格式。

square_rooted = sqrt(float(n))

还; 更改代码以显示值。使用 %s 代替数字 (%d)

"%s square rooted is %s."

样本:

Type number here: 81
81 square rooted is 9.0.
于 2019-05-30T14:48:57.213 回答
0

这对我有用,必须根据我的 python 版本修复语法-

from math import sqrt

n = input('Type number here: ')

n = float(n)

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)
于 2019-05-30T15:12:55.787 回答
0

如上所述,如果您是新手,python3 可能是更好的 python 版本,但 python 2 解决方案如下所示。我们使用 %f 表示我们的数字是一个浮点数。此外,在第 2 行,我们将 raw_input() 语句包装在 float() 函数中。这允许 python 解释器理解我们期望一个浮点值。

from math import sqrt

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)

python 3 版本将低于一些小的编辑。输入行现在将变为 input() 而不是 raw_input() ... print 语句将在两侧使用括号:

from math import sqrt

n =float(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)
于 2019-05-30T15:04:04.270 回答