求二次方程

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
Run Code Online (Sandbox Code Playgroud)

Ble*_*der 19

这条线导致了问题:

(-b+math.sqrt(b**2-4*a*c))/2*a
Run Code Online (Sandbox Code Playgroud)

x/2*a被解释为(x/2)*a.你需要更多的括号:

(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)
Run Code Online (Sandbox Code Playgroud)

此外,如果您已经存储d,为什么不使用它?

x = (-b + math.sqrt(d)) / (2 * a)
Run Code Online (Sandbox Code Playgroud)

  • 哇...我试图弄清楚一个多小时。非常感谢Blender。第二部分带有“ d”变量也很有帮助。 (2认同)

小智 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)
Run Code Online (Sandbox Code Playgroud)

  • 对于 d == 0,您应该将 2*a 放在括号中 (2认同)