无法在 python 3 上将复杂转换为浮动



我为uri在线判断编写此代码(问题编号1036(...这是婆什罗的公式...

import cmath
A,B,C=input().split()
A = float(A)
B = float(B)
C = float(C)
D = (B*B)-(4*A*C)
if((D== -D)|(A==0)):
print("Impossivel calcular")
else:
T = cmath.sqrt(D)
x1 = (-B+T)/(2*A)
x2 = (-B-T)/(2*A)
print("R1 = %.5f" %x1)
print("R2 = %.5f" %x2)

但是当我提交这个程序时...发生了运行时错误...

Traceback (most recent call last): File "Main.py", line 14, in
print("R1 = %.5f" %x1)
TypeError: can't convert complex to float
Command exited with non-zero status (1)

请帮我解决这个问题。

使用从cmath导入的sqrt的问题在于它输出一个complex数字,该数字无法转换为float。如果要根据正数计算sqrt,请使用math库(见下文(。

>>> from cmath import sqrt
>>> sqrt(2)
(1.4142135623730951+0j)
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951

问题只是您的格式字符串适用于floats而不是复数。 这样的东西会起作用:

print('{:#.3} '.format(5.1234 + 4.123455j))
# (5.12+4.12j) 

或 - 更明确:

print('{0.real:.3f} + {0.imag:.3f}i'.format(5.123456789 + 4.1234556547643j))
# 5.123 + 4.123i

你可能想看看格式规范迷你语言。

#作为格式说明符不适用于旧式%格式...

然后你的代码还有更多问题:

if((D== -D)|(A==0)):

为什么不if D==0:? 为此,最好使用cmath.isclose.

then:|是按位运算符,就像你使用它一样;你可能想用or替换它。

您的if语句可能如下所示:

if D == 0 or A == 0:
# or maybe
# if D.isclose(0) or A.isclose():

最新更新