.求方程ax²+bx+c=0的根,用3个函数分别求当:b2一4ac大于0、等于0和小于0 时的根并输出结果。从主函数输人a,6,c的值。
时间: 2023-10-06 13:06:39 浏览: 55
以下是实现该功能的代码:
```python
import math
def solve_real_roots(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
def solve_complex_roots(a, b, c):
delta = b**2 - 4*a*c
if delta > 0:
return None
elif delta == 0:
return None
else:
real_part = -b / (2*a)
imag_part = math.sqrt(-delta) / (2*a)
return complex(real_part, imag_part), complex(real_part, -imag_part)
def solve_equation(a, b, c):
if b**2 - 4*a*c > 0:
roots = solve_real_roots(a, b, c)
print("The equation has two real roots: x1 = {}, x2 = {}".format(*roots))
elif b**2 - 4*a*c == 0:
roots = solve_real_roots(a, b, c)
print("The equation has one real root: x = {}".format(*roots))
else:
roots = solve_complex_roots(a, b, c)
print("The equation has two complex roots: x1 = {}, x2 = {}".format(*roots))
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
solve_equation(a, b, c)
```
运行结果示例:
```
Enter a: 2
Enter b: 5
Enter c: 2
The equation has two real roots: x1 = -0.5, x2 = -2.0
```
```
Enter a: 1
Enter b: 4
Enter c: 4
The equation has one real root: x = -2.0
```
```
Enter a: 1
Enter b: 2
Enter c: 3
The equation has two complex roots: x1 = (-1+1.4142135623730951j), x2 = (-1-1.4142135623730951j)
```