输入三个数用python解一元二次方程
时间: 2024-10-23 08:14:38 浏览: 33
在Python中,可以使用`cmath`模块来解决一元二次方程,因为它的`sqrt()`函数可以处理复数根的情况。这里是一个简单的示例,它接受三个输入(a、b和c),用于计算一元二次方程ax² + bx + c = 0的解:
```python
import cmath
def solve_quadratic_equation(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)
return (root1, root2)
elif discriminant == 0:
root = -b / (2 * a)
return (root,)
else: # 复数根
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
return (real_part + imaginary_part * 1j, real_part - imaginary_part * 1j)
# 示例使用
a = float(input("请输入系数a: "))
b = float(input("请输入系数b: "))
c = float(input("请输入系数c: "))
solutions = solve_quadratic_equation(a, b, c)
print(f"一元二次方程的解为: {solutions}")
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)