TypeError:需要浮点数 - 使用pow()和math.sqrt()时

时间:2014-06-13 02:30:59

标签: python

当我尝试使用我的二次公式程序时,我不断收到此错误消息:

Traceback (most recent call last):
  File "C:\Python33\i=1000000000000.py", line 6, in <module>
    d = (pow(b,2)-4*a*c)
TypeError: a float is required

这里究竟出现了什么问题以及如何解决这个问题?

继承实际代码

import math
print("this is a quadratic formula application.")
a = input("Enter 'a' value: ")
b = input("Enter 'b' value: ")
c = input("Enter 'c' value: ")
d = (pow(b,2)-4*a*c)

if d < 0:
    print("there is no answer")
elif d == 0:
    print("There is only one answer: ",x)
    x =( -b + (d))/ (2*a)
else:
    print(" There are two answers: ",x1,"and ",x2)
    x1 =( -b + (sqrt(d,2)))/ (2*a)
    x2 =( -b - (sqrt(d,2)))/ (2*a)

1 个答案:

答案 0 :(得分:0)

input在Python 3.x中返回一个字符串对象。您需要将其显式转换为数字对象:

a = float(input("Enter 'a' value: "))
b = float(input("Enter 'b' value: "))
c = float(input("Enter 'c' value: "))

否则,您将为math.pow提供一个字符串:

>>> import math
>>>
>>> a = input("Enter 'a' value: ")
Enter 'a' value: 2
>>> math.pow(a, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required
>>>
>>> a = float(input("Enter 'a' value: "))
Enter 'a' value: 2
>>> math.pow(a, 2)
4.0
>>>