使用python的二次公式

使用python的二次公式,python,Python,尝试创建一个程序,其中包含三个参数,分别表示二次公式中的a、b和c值。数值应精确到小数点后两位。您不需要考虑虚拟值。然后在表格中打印出两个根: The solutions are x and y 其中,x和y分别对应于正根和负根 我的代码有问题: import math a = float(input('please input a number:')) b = float(input('please input a number3:')) c = float(input('please i

尝试创建一个程序,其中包含三个参数,分别表示二次公式中的a、b和c值。数值应精确到小数点后两位。您不需要考虑虚拟值。然后在表格中打印出两个根:

The solutions are x and y
其中,
x
y
分别对应于正根和负根

我的代码有问题:

import math

a = float(input('please input a number:'))
b = float(input('please input a number3:'))
c = float(input('please input a number2:'))
d = (b**2) - (4*a*c)

sol1 = str(round((-b-cmath.sqrt(d))/(2*a),2))
sol2 = str(round((-b+cmath.sqrt(d))/(2*a),2))

print('The solution are {1.real:.2f} and {0.real:.2f}'.format(sol1,sol2))

在代码中,您导入了数学,但使用了cmath。但是,一个更简单的解决方案是不导入任何东西并使用内置的幂函数。此外,python自己处理整数、浮点数和复数的打印,所以您不需要担心强制转换

试试这个:

# Get inputs
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

# Calculate discriminant
discriminant = b**2 - 4*a*c

# Get solutions, x^0.5 = square root
x1 = (-b + discriminant**0.5) / (2*a)
x2 = (-b - discriminant**0.5) / (2*a)

# Output
print(f"Solutions: {x1} and {x2}")

您正在强制您将结果设置为字符串(
str(round(…)
),然后在打印时询问它们的真实部分。它们不再是复数;它们是字符串。不需要调用
str
round
format
方法将负责将浮点值转换为字符串,并在过程中将浮点值四舍五入到所需的小数位数。不要只发布代码。请解释出了什么问题以及您是如何修复的。很抱歉,我现在添加了一个解释。您知道
cmath
对于处理复数更精确,是吗<代码>cmath.sqrt(-1)是
1j
,而
(-1)**0.5
(6.123233995736766e-17+1j)