我的代码在python 2.7中计算二次方程有什么问题?

时间:2017-07-31 12:59:45

标签: python python-2.7 math quadratic

def quad(a, b, c):
    solution1 = (-b + ((b**2 - 4 * a * c)**0.5)) / 2 * a
    solution2 = (-b - ((b**2 - 4 * a * c)**0.5)) / 2 * a
    return solution1, solution2

while True:
    print "\nax^2 + bx + c = 0"
    a = input("What does 'a' equal? ")
    b = input("What does 'b' equal? ")
    c = input("What does 'c' equal? ")

    answera, answerb = quad(a, b, c)
    print "(x -", str(answera) + ")(x -", str(answerb) + ") = 0"
    print "x=" + str(answera) + ",x=" + str(answerb)

该代码适用于' b'和' c',(在合理范围内),但无论什么时候' a'不过是1,代码给出了错误的数字,我无法弄清楚它有什么问题。

2 个答案:

答案 0 :(得分:8)

当你写DataSource时,你首先除以2,然后乘以/ 2 * a

您想要改为编写a

答案 1 :(得分:3)

按照操作顺序,在您的陈述中

/ (2 * a)

,首先进行除2,然后将结果乘以solution1 = (-b + ((b**2 - 4 * a * c)**0.5)) / 2 * a 。这不是你想要的:你希望a的结果分成其余部分。通过在括号周围加括号来解决这个问题:

2*a