本题要求编写程序,计算2个复数的和、差、积、商。
输入格式:
输入在一行中按照a1 b1 a2 b2
的格式给出2个复数C1=a1+b1i
和C2=a2+b2i
的实部和虚部。题目保证C2不为0。
输出格式:
分别在4行中按照(a1+b1i) 运算符 (a2+b2i) = 结果
的格式顺序输出2个复数的和、差、积、商,数字精确到小数点后1位。如果结果的实部或者虚部为0,则不输出。如果结果为0,则输出0.0。
题目分析:
python 可以直接用复数做四则运算,捡了个大便宜,但比较坑的是 python 用 j 表示虚数单位,和用 i 表示虚数单位的数学习惯不一样,需要转换一下。
#test7-36.py
# in this function the parameter type is str
def userComplex(real, imag):
if eval(imag)<0:
z = real + imag + "j"
else:
z = real + "+" + imag + "j"
return eval(z)
# in this function the parameter type is complex
def resultFormat(z):
if z.real == 0 and z.imag == 0:
print("0.0")
elif z.real == 0 and z.imag != 0:
print("{:.1f}i".format(z.imag))
elif z.real != 0 and z.imag == 0:
print("{:.1f}".format(z.real))
else:
if z.imag < 0:
print("{:.1f}".format(z.real) + "{:.1f}i".format(z.imag))
else:
print("{:.1f}".format(z.real) + "+" + "{:.1f}i".format(z.imag))
# in this function the parameter type is complex
def userFormat(z):
a = "{:.1f}".format(z)
a = a[0:-1] + "i"
a = "("+a+")"
return a
userInput = input().split()
z1 = userComplex(userInput[0], userInput[1])
z2 = userComplex(userInput[2], userInput[3])
a1 = userFormat(z1)
a2 = userFormat(z2)
sum = eval("{:.1f}".format(z1 + z2))
diff = eval("{:.1f}".format(z1 - z2))
product = eval("{:.1f}".format(z1 * z2))
quotient = eval("{:.1f}".format(z1 / z2))
result = [sum, diff, product, quotient]
oper = [" + "," - "," * "," / "]
for i in range(4):
print(a1+oper[i]+a2+" = ", end="")
resultFormat(result[i])