Home > Net >  Issue with Quadratic Equation Calculator in Python
Issue with Quadratic Equation Calculator in Python

Time:02-20

The weird thing is that my code works perfectly fine but if coefficient A is bigger than 1 my code doesn't work properly I rechecked my code but I couldn't find a bug.

This is my code-

 A= float(input("Coefficient A="))
B= float(input("Coefficient B="))
C= float(input("Coefficient C="))
y = B**2-4*A*C
y2 = -B-y**0.5
y3 = -B y**0.5
x = y2/ 2*A
x1 = y3/2*A
print("The answer is x=",x,"or",x1)

CodePudding user response:

You forgot parenthesis around 2*A when computing x and x1. Try to do:

x = y2/ (2*A)
x1 = y3/ (2*A)

CodePudding user response:

Operator precedence is at play here, which refers to which operator is executed first when python interpreter solves expressions, this can simply be solved by using brackets to further stress which operations must be done first. The major problem is in these lines of your code -:

x = y2/ 2*A
x1 = y3/2*A

The reason behind your problem, is that both the asterisk('*') operator for multiplication and the slash('/') operator for division have equal precedence thus python interpreter solves from left to right(as mentioned here), this makes the division statement get executed first that is -: (y2/2) or (y3/2). After that it multiplies the result with 2 as the asterisk comes later in the expression.

This can be solved by by putting brackets as they guide python as to which expressions to execute first.

But it is still suggested, and generally a good practice to use brackets to specify operations always that prevents such errors.

Adding brackets will change the lines to -:

x = y2/(2*A)
x1 = y3/(2*A)

With the full code being formatted to include brackets, it will look something like this -:

A = float(input("Coefficient A ="))
B = float(input("Coefficient B ="))
C = float(input("Coefficient C ="))
y = (B ** 2) - (4 * A * C)
y2 = (-B) - (y ** 0.5)
y3 = (-B)   (y ** 0.5)
x = y2 / (2 * A)
x1 = y3 / (2 * A)
print("The answer is x =", x, "or", x1)
  • Related