Discuss / Python / 再修改一版

再修改一版

Topic source

yayayaxs

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

修改了一版,这次考虑得比较全,只是验证a, b, c的合法性的方法还不是很好,当有两个以上的数不合法时每次只报错一个,大家有其它好方法的麻烦告知一下


# -*- coding: utf-8 -*-
import math

a = float(input('please input a = '))
b = float(input('please input b = '))
c = float(input('please input c = '))

def quadratic(a, b, c):
    if not isinstance (a, (int, float)):
        raise TypeError ('error aaaaaa')
    if not isinstance (b, (int, float)):
        raise TypeError ('error bbbbbb')
    if not isinstance (c, (int, float)):
        raise TypeError ('error cccccc')
    delta = b*b-4*a*c
    if a == 0:
        x1 = -c/b
        return x1
    elif (delta) > 0:
        x1 = (-b + math.sqrt(delta)) / (2*a)
        x2 = (-b - math.sqrt(delta)) / (2*a)
        return x1, x2
    elif (delta) == 0:
        x1 = -b / (2*a)
        return x1
    else:
        print ("无实数解")

print(quadratic(a, b, c))

  • 1

Reply