我正在尝试创建一个将使用二次公式求解x的代码。对于输出,我不希望它显示虚数...仅显示实数。我将平方根内的值设置为等于称为“ root”的变量,以确定此值是否为pos / neg(如果为负,则解为虚数)。
这是代码。
import math
print("Solve for x when ax^2 + bx + c = 0")
a = float(input("Enter a numerical value for a: "))
b = float(input("Enter a numerical value for b: "))
c = float(input("Enter a numerical value for c: "))
root = math.pow(b,2) - 4*a*c
root2 = ((-1*b) - math.sqrt(root)) / (2*a)
root1 = ((-1*b) + math.sqrt(root)) / (2*a)
for y in root1:
if root>=0:
print("x =", y)
elif root<0:
print('x is an imaginary number')
for z in root2:
if root>=0:
print("or x =", z)
elif root<0:
print('x is an imaginary number')
这是错误代码:
File "/Users/e/Documents/Intro Python 2020/Project 1/Project 1 - P2.py", line 25, in <module>
for y in root1:
TypeError: 'float' object is not iterable
错误发生在该行:
for y in root1:
如何解决此错误?
我了解您在这里使用二次方程。一个可迭代的东西就像一个列表。一个具有1个以上元素的变量。在您的示例中
root1是单个浮点值。 root2也是单个浮点值。为了您的目的,您不需要在“ for”行中添加任何一行。尝试删除for y和for z行并运行您的代码。
为了帮助您理解,浮点值就是带小数的数字。
嗯,该错误很容易解释:您试图遍历浮点数而不是列表的root1
和root2
。
我相信您想做的只是使用if / else块:
if root >= 0:
print("x =", root1)
print("x =", root2)
else:
print("x is an imaginary number")