为什么显示“ TypeError:需要浮点数”?

时间:2019-05-30 14:44:08

标签: python

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

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 个答案:

答案 0 :(得分:2)

您的代码存在一些问题/修复程序

  • 您需要转换从raw_input

  • 获得的字符串
  • 要显示浮动,请使用%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.

答案 1 :(得分:2)

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

square_rooted = sqrt(float(n))

也;在显示值时更改代码。使用%s代替数字(%d)

"%s square rooted is %s."

示例:

Type number here: 81
81 square rooted is 9.0.

答案 2 :(得分:0)

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

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)

答案 3 :(得分: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)