本文介绍了求解二次方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程序似乎没有给我正确的解决方案.有时会,有时不会.我找不到我的错误.有什么建议吗?
My program doesn't seem to give me the right solutions. Sometimes it does, sometimes it doesn't. I can't find my error. Any Suggestions?
import math
a,b,c = input("Enter the coefficients of a, b and c separated by commas: ")
d = b**2-4*a*c # discriminant
if d < 0:
print "This equation has no real solution"
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print "This equation has one solutions: ", x
else:
x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
x2 = (-b-math.sqrt(b**2-4*a*c))/2*a
print "This equation has two solutions: ", x1, " and", x2
推荐答案
此行导致问题:
(-b+math.sqrt(b**2-4*a*c))/2*a
x/2*a
被解释为 (x/2)*a
.您需要更多括号:
x/2*a
is interpreted as (x/2)*a
. You need more parentheses:
(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)
另外,如果您已经在存储 d
,为什么不使用它?
Also, if you're already storing d
, why not use it?
x = (-b + math.sqrt(d)) / (2 * a)
这篇关于求解二次方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!