python求解ax² + bx + c = 0


系数需满足条件:
  • a,b不能同时为0
  • b2-4ac≠0

代码如下
def quadratic(a, b, c):
""" 返回ax² + bx + c = 0的 """ if not all(map(lambda x: isinstance(x, (int, float)), (a, b, c))): raise TypeError('参数类型只能为int, float') if a == 0 and b == 0: return None # a, b不能同时为0 elif a == 0 and b != 0: return c / b elif a != 0 and b == 0: return math.sqrt(c / a) else: d = b**2 - 4*a*c if d <0 : return None # b²-4ac不能为0 else: return (-b + math.sqrt(d)) / 2*a, (-b - math.sqrt(d)) / 2*a
原文地址:https://www.cnblogs.com/seastar1989/p/5687989.html