python练习题1-一元二次方程解

import math

# 一元二次方程: a*x**2 + b*x + c =0的解
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不是整数

猜你喜欢

转载自www.cnblogs.com/babysteps/p/python_exercise1.html
今日推荐