用python语言写一个一元二次方程解的代码
时间: 2023-05-29 22:07:18 浏览: 82
下面是一个简单的一元二次方程求解代码:
```python
import math
def quadratic_equation(a, b, c):
delta = b ** 2 - 4 * a * c
if delta < 0:
return None
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
# 测试
print(quadratic_equation(1, -4, 4)) # -2.0
print(quadratic_equation(1, 2, 1)) # -1.0
print(quadratic_equation(1, 1, 1)) # None
```
其中,quadratic_equation函数接受三个参数a、b、c,分别代表一元二次方程的系数,返回方程的根。如果方程无解,则返回None。
相关问题
用python写一个一元二次方程解代码
以下是用Python编写的一元二次方程求解代码:
```python
import math
def quadratic(a, b, c):
"""
求解一元二次方程 ax^2 + bx + c = 0 的根
"""
delta = b * b - 4 * a * c
if delta < 0:
return None
elif delta == 0:
return -b / (2 * a)
else:
x1 = (-b + math.sqrt(delta)) / (2 * a)
x2 = (-b - math.sqrt(delta)) / (2 * a)
return x1, x2
# 测试代码
print(quadratic(1, -2, 1)) # (1.0,)
print(quadratic(1, 2, 1)) # (-1.0,)
print(quadratic(1, 3, 2)) # (-1.0, -2.0)
print(quadratic(1, 2, 3)) # None
```
在此代码中,我们定义了一个名为`quadratic`的函数,该函数接受三个参数:`a`,`b`和`c`,这些参数分别代表一元二次方程的系数。然后,我们计算方程的判别式`delta`,并检查其值。如果`delta`小于0,则方程没有实根,我们返回`None`;如果`delta`等于0,则方程有一个实根,我们返回该根;否则,方程有两个实根,我们返回这两个根。
最后,我们使用`print`函数测试了这个函数,并打印出了它的返回值。
用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 环境中运行,然后输入对应的系数,即可得到一元二次方程的解。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)