我想知道是否有人能告诉我为什么我的用于求解二次方程的 python 代码不起作用。我已经检查过了,没有发现任何错误。
print("This program will solve quadratic equations for you")
print("It uses the system 'ax**2 + bx + c'")
print("a, b and c are all numbers with or without decimal \
points")
print("Firstly, what is the value of a?")
a = float(input("\n\nType in the coefficient of x squared"))
b = float(input("\n\nNow for b. Type in the coefficient of x"))
c = float(input("\n\nGreat. now what is the c value? The number alone?"))
print("The first value for x is " ,(-b+(((b**2)-(4*a* c))* * 0.5)/(2*a)))
print("\n\nThe second value for x is " ,(-b-(((b * * 2)-(4*a*c))** 0.5)/(2*a)))
当 a=1 b=-4 和 c=-3 时,我期待 -1 和 4,但得到 5.5 和 0.5
您的麻烦在于尝试执行二次公式的部分:
(-b+(((b**2)-(4*a* c))* * 0.5)/2*a)
麻烦的是*
具有相同的优先级/
所以你先除以 2,然后乘以a
。而且你的括号也被去掉了,所以我减少了不必要的括号并移动了错误的括号。简而言之,-b 在除法之前没有与平方根放在一起。你想要的是:
(-b+(b**2-4*a*c)**0.5)/(2*a)
附:为了提出问题,最好以以下形式提出:
>>> a = 2
>>> b = 1
>>> c = 3
>>> (-b+(((b**2)-(4*a* c))* * 0.5)/2*a)
got blah, expected blam
由于其他打印和输入不应该受到指责(您应该能够相当容易地解决)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)