我为 uri 在线法官编写此代码(问题编号 1036)...这是 Bhaskara 公式...
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)
Run Code Online (Sandbox Code Playgroud)
但是当我提交这个程序时...发生了运行时错误...
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)
Run Code Online (Sandbox Code Playgroud)
请帮我解决这个问题。
问题在于您的格式字符串适用于floats而不适用于复数。像这样的东西会起作用:
print('{:#.3} '.format(5.1234 + 4.123455j))
# (5.12+4.12j)
Run Code Online (Sandbox Code Playgroud)
或者 - 更明确:
print('{0.real:.3f} + {0.imag:.3f}i'.format(5.123456789 + 4.1234556547643j))
# 5.123 + 4.123i
Run Code Online (Sandbox Code Playgroud)
您可能想看看迷你语言的格式规范。
#因为格式说明符不适用于旧式格式%...
那么您的代码还有更多问题:
if((D== -D)|(A==0)):
Run Code Online (Sandbox Code Playgroud)
为什么不if D==0:?为此,使用 可能会更好cmath.isclose。
then:|是一个按位运算符,就像您使用它的方式一样;您可能想将其替换为or.
你的if声明可能如下所示:
if D == 0 or A == 0:
# or maybe
# if D.isclose(0) or A.isclose():
Run Code Online (Sandbox Code Playgroud)