求方程ax^2+bx+c=0的根,用三个函数分别求当:b^2-4ac大于0、等于0和小于0时的根并输出结果。从主函数输入a,b,c的值
时间: 2023-11-29 15:59:37 浏览: 262
以下是代码实现:
```python
import math
def solve_quadratic_greater(a, b, c):
delta = b**2 - 4*a*c
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
return x1, x2
def solve_quadratic_equal(a, b, c):
x = -b / (2*a)
return x
def solve_quadratic_less(a, b, c):
real = -b / (2*a)
imaginary = math.sqrt(abs(b**2 - 4*a*c)) / (2*a)
x1 = complex(real, imaginary)
x2 = complex(real, -imaginary)
return x1, x2
a = float(input("请输入a的值:"))
b = float(input("请输入b的值:"))
c = float(input("请输入c的值:"))
if b**2 - 4*a*c > 0:
x1, x2 = solve_quadratic_greater(a, b, c)
print("方程的两个实根分别为:", x1, x2)
elif b**2 - 4*a*c == 0:
x = solve_quadratic_equal(a, b, c)
print("方程的唯一实根为:", x)
else:
x1, x2 = solve_quadratic_less(a, b, c)
print("方程的两个复根分别为:", x1, x2)
```
输入a、b、c的值后,程序会根据$b^2-4ac$的值来选择不同的函数求解,输出对应的结果。
例如,当输入$a=1,b=2,c=1$时,$b^2-4ac=0$,程序输出:
```
方程的唯一实根为: -1.0
```
阅读全文