用python求一元二次方程的根,用“行”if语句和if语句的嵌套两种方法分别求解
时间: 2024-10-15 15:29:46 浏览: 42
在Python中,求解一元二次方程 \(ax^2 + bx + c = 0\) 的根,可以利用公式法,也可以通过数值计算库如`numpy`或者直接编写一些条件判断。以下是使用if语句和if语句的嵌套两种方法:
**方法一:if语句**
```python
import cmath
def quadratic_solver(a, b, c):
delta = (b ** 2) - (4 * a * c)
if delta > 0:
root1 = (- cmath.sqrt(delta)) / (2 * a)
print(f"两个实数根: {root1.real:.2f}, {root2.real:.2f}")
elif delta == 0:
root = -b / (2 * a)
print(f"唯一实数根: {root:.2f}")
else: # 当delta < 0,有两个复数根
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-delta) / (2 * a)
print(f"两个复数根: {real_part:.2f} + {imaginary_part:.2f}i, {real_part:.2f} - {imaginary_part:.2f}i")
# 调用函数并传入系数
quadratic_solver(1, -3, 2)
```
**方法二:if语句的嵌套**
```python
def quadratic_solver_nested(a, b, c):
discriminant = b ** 2 - 4 * a * c
if discriminant >= 0:
if discriminant == 0:
root = -b / (2 * a)
print("唯一实数根:", root)
else:
sqrt_discriminant = discriminant ** 0.5
root1 = (-b + sqrt_discriminant) / (2 * a)
root2 = (-b - sqrt_discriminant) / (2 * a)
print("两个实数根:", root1, root2)
else:
complex_part = discriminant ** 0.5
print("两个复数根:", (-b + complex_part * 1j) / (2 * a), "and", (-b - complex_part * 1j) / (2 * a))
# 使用同样的系数调用函数
quadratic_solver_nested(1, -3, 2)
```
阅读全文