沒有根的時候答案的代碼不會報錯嗎
import math
def quadratic_equation(a, b, c):
? ? t = math.sqrt(b*b-4*a*c)
? ? if t>0:
? ? ? ? x1 = (-b+t)/(2*a)
? ? ? ? x2 = (-b-t)/(2*a)
? ? ? ? return x1,x2
? ? elif t == 0:
? ? ? ? x1 = x2 = -b/(2*a)
? ? ? ? return x1,x2
? ? else:
? ? ? ? return("null")
print quadratic_equation(2, 3, 0)
print quadratic_equation(1, -6, 5)
2020-06-22
如果b*b-4*a*c小于零的話調用sqrt函數python會直接報錯,不需要自己判斷(如果硬要判斷的話你需要在進行sqrt函數之前判斷)
2020-04-18
import math
def quadratic_equation(a, b, c):
? ? r = b*b-4*a*c
? ? if r>0:
? ? ? ? t = math.sqrt(r)
? ? ? ? x1 = (-b+t)/(2*a)
? ? ? ? x2 = (-b-t)/(2*a)
? ? ? ? return x1,x2
? ? elif r == 0:
? ? ? ? x1 = x2 = -b/(2*a)
? ? ? ? return x1,x2
? ? else:
? ? ? ? return ("null")