TypeError:pow()和math.sqrt()需要浮点数

1 投票
1 回答
10480 浏览
提问于 2025-04-18 09:38

我在尝试使用我的二次方程程序时,总是收到这个错误信息:

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

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

撰写回答