我正在尝试创建一个函数来解决二次公式的根并将它们作为列表返回。我需要确保参数是数字。当a = 0时,它还必须求解根。
def quadratic_roots(a, b, c):
if type(a) != float and int:
print('All values must be a int or float. Bitch')
return None
if type(b) != float and int:
print('All values must be a int or float. Bitch')
return None
if type(c) != float and int:
print('All values must be a int or float. Bitch')
return None
else:
if a == 0:
root = (-c) / b
list_root = [root]
return list_root
elif a == 0 and b == 0:
empty = []
return empty
elif a == 0 and b == 0 and c == 0:
empty = []
return empty
else:
discriminant = (b ** 2) - 4 * a * c
root1 = ((-b) - ((discriminant)**.5))/(2*a)
root2 = ((-b) + ((discriminant)**.5))/(2*a)
if root1 > root2:
list_roots = [root2, root1]
return list_roots
elif root2 > root1:
list_roots = [root1, root2]
return list_roots
elif root1 == root2:
list_roots = [root1]
return list_roots
答案 0 :(得分:0)
我看到几个问题:
以下是我对代码的看法:
def quadratic_roots(a, b, c):
if type(a) != float and type(a) != int:
print('All values must be a int or float. Bitch')
return None
if type(b) != float and type(b) != int:
print('All values must be a int or float. Bitch')
return None
if type(c) != float and type(c) != int:
print('All values must be a int or float. Bitch')
return None
a = float(a)
b = float(b)
c = float(c)
if a == 0 and (b == 0 or c == 0):
return []
if a == 0:
root = (-c) / b
list_root = [root]
return list_root
discriminant = (b ** 2) - 4 * a * c
root1 = ((-b) - ((discriminant)**.5))/(2*a)
root2 = ((-b) + ((discriminant)**.5))/(2*a)
if root1 > root2:
list_roots = [root2, root1]
elif root2 > root1:
list_roots = [root1, root2]
else: # roots are equal
list_roots = [root1]
return list_roots