请用python编写求解一元二次方程的代码
时间: 2023-07-23 19:28:17 浏览: 66
当然可以,以下是用Python编写的一元二次方程求解代码:
```python
import cmath # 导入复数模块
a = float(input("请输入a的值:"))
b = float(input("请输入b的值:"))
c = float(input("请输入c的值:"))
# 计算根
d = (b ** 2) - (4 * a * c)
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
# 输出根
print("根1:", root1)
print("根2:", root2)
```
在代码中,我们使用 `input()` 函数来获取用户输入的系数 a、b、c 的值,然后根据一元二次方程的求根公式计算出根。需要注意的是,当判别式 D = b^2 - 4ac 小于 0 时,方程无实数解,需要使用复数模块 cmath 来求解。
相关问题
用PYTHON写一段一元二次方程求解的代码
当然可以,以下是一段用 Python 编写的一元二次方程求解代码:
```python
import math
def solve_quadratic_equation(a, b, c):
delta = b ** 2 - 4 * a * c
if delta < 0:
return "无实数解"
elif delta == 0:
x = -b / (2 * a)
return x
else:
x1 = (-b + math.sqrt(delta)) / (2 * a)
x2 = (-b - math.sqrt(delta)) / (2 * a)
return x1, x2
a = float(input("请输入一元二次方程的系数a: "))
b = float(input("请输入一元二次方程的系数b: "))
c = float(input("请输入一元二次方程的系数c: "))
result = solve_quadratic_equation(a, b, c)
print("方程的解为:", result)
```
你可以将上述代码复制到 Python 环境中运行,然后输入对应的系数,即可得到一元二次方程的解。
用python编写一个函数,求一元二次方程的根
以下是一个求解一元二次方程的根的Python函数:
```python
import math
def quadratic_equation(a, b, c):
"""
求一元二次方程的根
ax^2 + bx + c = 0
返回一个元组,包含两个根(可能相等)
"""
delta = b * b - 4 * a * c
if delta < 0:
return None
elif delta == 0:
x = -b / (2 * a)
return (x, x)
else:
sqrt_delta = math.sqrt(delta)
x1 = (-b + sqrt_delta) / (2 * a)
x2 = (-b - sqrt_delta) / (2 * a)
return (x1, x2)
# 示例
print(quadratic_equation(2, 3, 1)) # (-0.5, -1.0)
print(quadratic_equation(1, -6, 9)) # (3.0, 3.0)
print(quadratic_equation(1, 2, 3)) # None
```
在这个函数中,参数 `a`, `b`, `c` 分别表示一元二次方程的三个系数。函数首先计算判别式 `delta`,如果 `delta` 小于 0,则方程无实数根,函数返回 `None`;如果 `delta` 等于 0,则方程有一个实数根,函数返回一个长度为 1 的元组;如果 `delta` 大于 0,则方程有两个不同的实数根,函数返回一个长度为 2 的元组。函数中使用了 Python 标准库中的 `math.sqrt` 函数来计算平方根。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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://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://csdnimg.cn/download_wenku/file_type_ask_c1.png)