请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:ax² + bx + c = 0的两个解。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import math 4 def quadratic(a,b,c): 5 if a == 0: 6 raise TypeError('a不能为0') 7 if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)): 8 raise TypeError('Bad operand type') 9 delta = math.pow(b,2) - 4*a*c 10 if delta < 0: 11 return '无实根' 12 x1= (math.sqrt(delta)-b)/(2*a) 13 x2=-(math.sqrt(delta)+b)/(2*a) 14 return x1,x2 15 print(quadratic(2,3,1)) 16 print(quadratic(1,3,-4))
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15837.html