Everything in my program works except when it prints out "The solutions are: " s1
and s2
print out with a +0.00j
after the answer. How do I format the output to just be two decimal places? As you can see I tried the ,.2f
but it didn't work, any help would be appreciated.
import cmath
#converting inputs into floats to avoid ValueError
a = 0
while a == 0:
try:
a = float(input("Enter a value for a: "))
if a == 0:
raise ZeroDivisionError
except ZeroDivisionError:
print("The value you entered is invalid. Zero is not allowed")
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
while True:
try:
b = float(input("Enter a value for b: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
while True:
try:
c = float(input("Enter a value for c: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
#Calcualting discriminant, printing it and formatting it
disc = (b**2) - (4*a*c)
print("The discriminant is equal to: " , disc)
print()
#Calucating/printing solutions if there is one, two, or none
if disc < 0:
print ("No real solution")
elif disc == 0:
x = (-b+cmath.sqrt(disc))/(2*a)
print ("The solution is " , x)
else:
s1 = (-b+cmath.sqrt(disc))/(2*a)
s2 = (-b-cmath.sqrt(disc))/(2*a)
print ("The solutions are " + format(s1,",.2f"), "and " + format(s2, ",.2f"))
Just print out the .real
part of your complex numbers:
Change the relevant lines to
print(f"The solution is {x.real:.2f}")
and
print (f"The solutions are {s1.real:.2f} and {s2.real:.2f}")