# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
delta = b ** 2 - 4 * a * c
if delta < 0:
# print('无实数根')
return
elif delta == 0:
r = -b / (2 * a)
# print('有一个实数根%s' % r)
return r
else:
r1 = (-b + math.sqrt(delta)) / (2 * a)
r2 = (-b - math.sqrt(delta)) / (2 * a)
# print('有两个实数根%s %s' % (r1, r2))
return r1, r2
# 测试:
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))
if quadratic(2, 3, 1) != (-0.5, -1.0):
print('测试失败')
elif quadratic(1, 3, -4) != (1.0, -4.0):
print('测试失败')
else:
print('测试成功')
函数定义——一元二次方程求根
最新推荐文章于 2024-11-08 13:43:44 发布