Discuss / Python / 作业

作业

Topic source

LesLieM樂

#1 Created at ... [Delete] [Delete and Lock User]
在此插入代码

-- 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') r = b*2 - 4 a * c if r > 0:

    d = math.sqrt(r)
    x1 = (-b + d) / (2 * a)
    x2 = (-b - d) / (2 * a)
    print('有两个不同的实根')
    return x1, x2
elif r == 0:
    x1 = -b / (2 * a)
    x2 = x1
    print('有两个共轭实根')
    return x1, x2
else:
    print('无实根')

测试

print(quadratic(2, 3, 1)) x1, x2 = quadratic(1, 3, -4) print('x1 = %s\nx2 = %s'%(x1, x2)) print(quadratic(1, 2, 1)) print(quadratic(1, 1, 1))


  • 1

Reply