Python 二次公式函数
我试着做一个函数,求一个二次公式的根,然后把它们作为一个列表返回。我需要确保参数也是数字。当a=0时,它还必须求解根Python 二次公式函数,python,Python,我试着做一个函数,求一个二次公式的根,然后把它们作为一个列表返回。我需要确保参数也是数字。当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
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
我看到几个问题:
- 对float或int的检查不正确
- 答案为-c/b的情况不仅仅是当a==0时。当a为0且b和c均不为0时,则为。必须先检查一下
- 它不会中断程序,但是嵌套的if/elif/else在您总是从if返回时不起作用。在这种情况下,elif只是更高级别的if
- 如果不将操作数转换为浮点数,并且使用的是python 2,并且有-c/b的情况,那么如果这些是int,则将得到整数除法答案,而不是正确的浮点答案
- 你不是在处理假想根。我不知道你想在那里做什么,所以我也没有处理他们。只要知道这段代码不处理判别式为负的情况
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
你有什么问题?你的问题是什么?解决根的问题,我的问题是,当我运行二次_根(1,2,3)时,它不会将它们视为int/float