我为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():