为了练习,我试图构建一个简单的函数来解决二次根-包括复根,并返回一个漂亮的四舍五入的结果。然而,round()函数和f-string格式似乎都不起作用。
下面是我写的代码:from cmath import sqrt
a = float(input("Input ax^2: "))
b = float(input("Input bx: "))
c = float(input("Input c: "))
def quadratic_roots(a,b,c):
x_1 = (-b - sqrt((b ** 2) - (4 * a * c))) / (2 * a)
x_2 = (-b + sqrt((b ** 2) - (4 * a * c))) / (2 * a)
return x_1,x_2
print(f"--- {a}x^2 {b}x + {c} = 0 ----")
#Attempting to use round() fuction.
print(f"x_1 = {round(quadratic_roots(a,b,c)[0],2)}") #Produces error
print(f"x_2 = {round(quadratic_roots(a,b,c)[1],2)}") #Produces error
#Attempting to use f-string formatting .to round up to three digits.
print(f"x_1 = {quadratic_roots(a,b,c)[0]:.3d}") #Produces error
print(f"x_2 = {quadratic_roots(a,b,c)[1]:.3d}") #Produces error
下面是我得到的输出/错误信息:
print(f"x_1 = {round(quadratic_roots(a,b,c)[0],2)}")
TypeError: type complex doesn't define __round__ method
是否有人可以帮助我整理这个并将结果作为一个漂亮和四舍五入的结果返回?
欢迎任何帮助和感激:-)
问题在于round。我修复了这个问题,希望它现在可以工作了。
代码:
from cmath import sqrt
a = float(input("Input ax^2: "))
b = float(input("Input bx: "))
c = float(input("Input c: "))
def quadratic_roots(a,b,c):
x_1 = (-b - sqrt((b ** 2) - (4 * a * c))) / (2 * a)
x_2 = (-b + sqrt((b ** 2) - (4 * a * c))) / (2 * a)
return x_1, x_2
print(f"--- {a}x^2 {b}x + {c} = 0 ----")
x_1, x_2 = quadratic_roots(a,b,c)
#Attempting to use round()
print(f"x_1 = {round(x_1.real, 3) + round(x_1.imag, 3) * 1j}")
print(f"x_2 = {round(x_2.real, 3) + round(x_2.imag, 3) * 1j}")
#Attempting to use f-string formatting .to round up to three digits.
print(f"x_1 = {x_1:.3f}")
print(f"x_2 = {x_2:.3f}")
输入:
Input ax^2: 1
Input bx: 1
Input c: 1
输出:
--- 1.0x^2 1.0x + 1.0 = 0 ----
x_1 = (-0.5-0.866j)
x_2 = (-0.5+0.866j)
x_1 = -0.500-0.866j
x_2 = -0.500+0.866j
可以将实部和虚部分别四舍五入,然后将它们合起来
print(f"x_1 = {round(quadratic_roots(a,b,c[0].real,2)}+{round(quadratic_roots(a,b,c)[0].imag,2)*1j}")
print(f"x_2 = {round(quadratic_roots(a,b,c)[1].real,2)}+{round(quadratic_roots(a,b,c)[1].imag,2)*1j}")
复数有实部和虚部。
试题:
x_1 = quadratic_roots(a, b, c)[0].real + quadratic_roots(a, b, c)[0].imag
x_2 = quadratic_roots(a, b, c)[1].real + quadratic_roots(a, b, c)[1].imag
print(f"x_1 = {round(x_1,2)}")
print(f"x_2 = {round(x_2,2)}")
经过注释的帮助,这个问题通过使用
解决了。print(f"x_1 = {quadratic_roots(a,b,c)[0]:.3f}")
print(f"x_2 = {quadratic_roots(a,b,c)[1]:.3f}")
问题是我使用了错误的f-string格式:
我尝试使用f"{:.d}"
,这不起作用。将其替换为f"{:.f}"
就可以了。
然而,正如评论中所建议的,有更好的方法来解决这个问题。
非常感谢所有帮助和贡献的人!