用python解一元二次方程
时间: 2023-04-02 20:04:44 浏览: 67
可以使用以下代码解一元二次方程:
import math
a = float(input("请输入a的值:"))
b = float(input("请输入b的值:"))
c = float(input("请输入c的值:"))
delta = b**2 - 4*a*c
if delta < :
print("该方程无实数解")
elif delta == :
x = -b / (2*a)
print("该方程有唯一解,x =", x)
else:
x1 = (-b + math.sqrt(delta)) / (2*a)
x2 = (-b - math.sqrt(delta)) / (2*a)
print("该方程有两个实数解,分别为x1 =", x1, "和x2 =", x2)
相关问题
输入三个数用python解一元二次方程
在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}")
用python解一元二次方程 ax2+bx+c=0
Sure, here's the code to solve a quadratic equation in Python:
import cmath
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
# Calculate the discriminant
d = (b**2) - (4*a*c)
# Find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print("The solutions are {0} and {1}".format(sol1, sol2))
阅读全文