Discuss / Python / 参考其他答案修改后的代码,原来没有考虑任意解的情况

参考其他答案修改后的代码,原来没有考虑任意解的情况

Topic source

-- coding: utf-8 --

import math

def quadratic(a, b, c): if not isinstance(a, (int, float)): raise TypeError('bad operand type') if not isinstance(b, (int, float)): raise TypeError('bad operand type') if not isinstance(c, (int, float)): raise TypeError('bad operand type') d = bb-4ac if a==0 & b==0 & c==0: return '任意解' if d>=0: x1=(-b+math.sqrt(d))/(2a) x2=(-b-math.sqrt(d))/(2*a) return x1,x2 else: return '无实数解' print(quadratic(2, 3, 1)) # => (-0.5, -1.0) print(quadratic(1, 3, -4)) # => (1.0, -4.0)


  • 1

Reply