import cmath
import math
import sys
def get_float(msg,allow_zero):
x = None
while x is None:
try:
x = float(input(msg))
if not allow_zero and abs(x) < sys.float_info.epsilon: #float_info.epsilon为接近0值的浮点数,因计算机浮点数只能无限接近0
print("zero is not allowed")
x = None
except ValueError as err:
print(err)
return x
print("ax2 + bx +c = 0")
a = get_float("enter a:",False)
b = get_float("enter b:",True)
c = get_float("enter c:",True)
x1 = None
x2 = None
discriminant = (b ** 2) - (4*a*c)
if discriminant == 0:
x1 = -(b/(2*a))
print(x1)
else:
if discriminant > 0:
root = math.sqrt(discriminant)
else:
root = cmath.sqrt(discriminant) #cmath为复数形式
x1 = (-b+root)/(2*a)
x2 = (-b-root)/(2*a)
print(x1)
print(x2)