Discuss / Python / 应该ok~

应该ok~

Topic source

most_逐

#1 Created at ... [Delete] [Delete and Lock User]
def quadratic(a,b,c):
    if not isinstance(a,(int,float)):
        raise TypeError('bad oprand type')
    elif not isinstance(b,(int,float)):
        raise TypeError('bad oprand type')
    elif not isinstance(c,(int,float)):    
        raise TypeError('bad oprand type')
    else:
        pass
    derta=b**2-4*a*c
    derta=float(derta)
    if a == 0:
        x=-(c/b)
    else:
        if b == 0:
            x1=math.sqrt(c/a)
            x2=-math.sqrt(c/a)
            x=x1,x2
        else:
            if derta <0:
                x="方程无实数解"
            elif derta ==0:
                x=(-b)/(2*a)
            else:
                x1=((-b)+math.sqrt(derta))/(2*a)
                x2=((-b)-math.sqrt(derta))/(2*a)
                x=x1,x2
    return x

most_逐

#2 Created at ... [Delete] [Delete and Lock User]

if b==0的那里忘记要加绝对值了。。改一下

import math
def quadratic(a,b,c):
    if not isinstance(a,(int,float)):
        raise TypeError('bad oprand type')
    elif not isinstance(b,(int,float)):
        raise TypeError('bad oprand type')
    elif not isinstance(c,(int,float)):    
        raise TypeError('bad oprand type')
    else:
        pass
    derta=b**2-4*a*c
    derta=float(derta)
    if a == 0:
        x=-(c/b)
    else:
        if b == 0:
            q=c/a
            x1=math.sqrt(abs(c/a))
            x2=-x1
            x=x1,x2
        else:
            if derta <0:
                x="方程无实数解"
            elif derta ==0:
                x=(-b)/(2*a)
            else:
                x1=((-b)+math.sqrt(derta))/(2*a)
                x2=((-b)-math.sqrt(derta))/(2*a)
                x=x1,x2
    return x

yayayaxs

#3 Created at ... [Delete] [Delete and Lock User]

但是这样检查a, b, c的合法性并不是很好,当有多个数不合法的时候,一次只能提示一个错误


  • 1

Reply