3. 在Python3中通过输入一元二次函数方程组的系数,在屏幕上显示方程式以及两个根 ax2+bx+c=0 (a,b,c)=(1,4,1), (1,2,3),(2,3,5)
时间: 2024-09-29 10:13:40 浏览: 29
python解二元二次方程代码.docx
在Python3中,你可以创建一个函数来接收一元二次方程的系数,并计算并显示其解。这里是一个简单的例子,展示如何处理给定的三个方程:
```python
import cmath
def quadratic_solver(a, b, c):
# 计算判别式
discriminant = (b**2) - (4*a*c)
roots = []
if discriminant > 0:
root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
roots.append(root1.real)
roots.append(root2.real)
elif discriminant == 0:
root = -b / (2 * a)
roots.append(root)
else:
real_part = -b / (2 * a)
imaginary_part = cmath.sqrt(-discriminant) / (2 * a)
roots.append(real_part)
roots.append(imaginary_part)
print(f"对于方程 {a}x^2 + {b}x + {c} = 0 的解是:")
for i, root in enumerate(roots):
print(f"根{i+1}: {root}")
# 给定的方程系数
coefficients_list = [(1, 4, 1), (1, 2, 3), (2, 3, 5)]
for coefficients in coefficients_list:
quadratic_solver(*coefficients)
阅读全文