一元二次方程: $ ax^2 + bx + c = 0 $ 的解
import math
def f(a, b, c):
if not isinstance(a, (int, float)):
raise TypeError("a不是数值型")
if not isinstance(b, (int, float)):
raise TypeError("b不是数值型")
if not isinstance(c, (int, float)):
raise TypeError("c不是数值型")
d = b**2 - 4 *a * c
if a == 0:
if b == 0:
if c == 0:
return '方程根为全体实数'
else:
return '方程无根'
else:
x1 = -c / b
return x1
else:
if d < 0:
return '方程无根'
else:
x1 = (-b + math.sqrt(d)) / 2 / a
x2 = (-b - math.sqrt(d)) / 2 / a
return x1,x2
测试f(1, 3, 2)
(-1.0, -2.0)
f(1, 1, 1)
'方程无根'
f(0, 1, 2)
-2.0
f(0, 0, 3)
'方程无根'
f(0, 0, 0)
'方程根为全体实数'
f('a','b','c')
a不是整数