2.求方程ax²+bx+c=0的根,用3个函数分别求当:b^2-4ac大于0、等于0和小于0
时间: 2023-06-02 19:06:57 浏览: 208
当 b^2-4ac 大于0 时,方程有两个实根,可以用以下公式求解:
x1 = (-b + sqrt(b^2 - 4ac)) / (2a)
x2 = (-b - sqrt(b^2 - 4ac)) / (2a)
其中 sqrt 表示求平方根。函数实现如下:
```python
import math
def solve_equation(a, b, c):
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return x1, x2
elif delta == 0:
x = -b / (2*a)
return x,
else:
return None
```
当 b^2-4ac 等于0 时,方程有一个实根,可以用以下公式求解:
x = -b / (2a)
函数实现如下:
```python
def solve_equation(a, b, c):
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return x1, x2
elif delta == 0:
x = -b / (2*a)
return x,
else:
return None
```
当 b^2-4ac 小于0 时,方程无实根,可以用以下公式求解:
x1 = (-b + sqrt(-delta)) / (2a)i
x2 = (-b - sqrt(-delta)) / (2a)i
其中 i 表示虚数单位。函数实现如下:
```python
def solve_equation(a, b, c):
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return x1, x2
elif delta == 0:
x = -b / (2*a)
return x,
else:
x1 = (-b + math.sqrt(-delta)) / (2*a)*1j
x2 = (-b - math.sqrt(-delta)) / (2*a)*1j
return x1, x2
```
阅读全文