用python求一元二次方程的根的值,用“行”if语句和if语句的嵌套两种方法分别求解
时间: 2024-10-15 17:29:49 浏览: 17
在Python中,我们可以使用`cmath`模块来处理复数,因为一元二次方程可能会有实根或复根。一元二次方程的一般形式是ax^2 + bx + c = 0,其中a、b和c是常数,x是我们要找的解。
以下是使用`if`语句和if语句嵌套两种方法求解一元二次方程的根:
**方法一:如果-布里渊条件满足(实根)**
```python
import cmath
def solve_quadratic(a, b, c):
delta = (b ** 2) - (4 * a * c)
if delta >= 0: # 实根情况
root1 = (-b + cmath.sqrt(delta)) / (2 * a)
root2 = (-b - cmath.sqrt(delta)) / (2 * a)
print(f"Roots are: {root1:.2f} and {root2:.2f}")
else: # 复根情况
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-delta) / (2 * a)
print(f"Roots are complex conjugates: {real_part:.2f} + {imaginary_part:.2f}i and {real_part:.2f} - {imaginary_part:.2f}i")
# 调用函数并传入系数
solve_quadratic(1, -3, 2)
```
**方法二:使用if嵌套(同时处理实根和复根)**
```python
def solve_quadratic_if_nested(a, b, c):
discriminant = b ** 2 - 4 * a * c
if discriminant > 0:
root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
print(f"Roots are: {root1:.2f}, {root2:.2f}")
elif discriminant == 0:
root = -b / (2 * a)
print(f"Single root is: {root:.2f}")
else: # 复根情况
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
print(f"Roots are complex conjugates: {real_part:.2f} + {imaginary_part:.2f}i and {real_part:.2f} - {imaginary_part:.2f}i")
# 调用函数并传入系数
solve_quadratic_if_nested(1, -3, 2)
```
这两种方法都首先计算判别式`delta`,然后根据其正负来判断方程的根性质。注意,`sqrt`会返回复数结果,所以需要使用`cmath.sqrt`来处理负数的情况。
阅读全文