13 python python-2.7
我的程序似乎没有给我正确的解决方案.有时确实如此,有时却没有.我找不到我的错误.有什么建议?
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
Ble*_*der 19
这条线导致了问题:
(-b+math.sqrt(b**2-4*a*c))/2*a
x/2*a被解释为(x/2)*a.你需要更多的括号:
(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)
此外,如果您已经存储d,为什么不使用它?
x = (-b + math.sqrt(d)) / (2 * a)
小智 6
在这里,你应该每次都给你正确的答案!
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
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, " or", x2)