-1
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)

The code works for any numbers on 'b' and 'c', (within reason), but whenever 'a' is anything but 1, the code gives the wrong numbers, and I can't figure out what's wrong with it.

  • 1
    Can you provide sample input (working and failing), current result, desired result and an explanation of the failure? – Yunnosch Jul 31 '17 at 13:02

2 Answers2

7

When you write / 2 * a you first divide by 2, then multiply by a.

You want to write / (2 * a) instead.

Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
3

In the order of operations, in your statement

solution1 = (-b + ((b**2 - 4 * a * c)**0.5)) / 2 * a

, the division by 2 is done first, then the multiplication of that result by a. That is not what you want: you want the result of 2*a divided into the rest. Solve this by putting parentheses around the denominator:

solution1 = (-b + ((b**2 - 4 * a * c)**0.5)) / (2 * a)
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50