python3中提供复数类型[1],其创建可通过complex([real[, imag]])
,当两者都缺省时,返回0j
。该类型[2]可处理+
、_
、*
、/
四种运算;若c
为复数类型,则c.real
表示实部,c.imag
表示虚部,还可以通过c.conjugate()
求其共轭复数。
至于为啥python3中复数中用表示而不是。可以参考这份介绍[3]。
以下是编程题。本题如果通过自己编程实现题干中的四舍五入并不可行,反而通过控制float
类型输出格式便可。极其感谢此文[4]作者。
# PAT中的基础编程题目集函数题7-36
def printPatOfRes(pattern, real, image, a1, b1, a2, b2): # 用于输出
if image <= 0.05 and image >=-0.05:
pattern += '%.1f'
print(pattern %(a1, b1, a2, b2, real))
elif real <= 0.05 and real >= -0.05:
pattern += '%.1fi'
print(pattern %(a1, b1, a2, b2, image))
elif image < 0 :
pattern += '%.1f%.1fi'
print(pattern %(a1, b1, a2, b2, real, image) )
else :
pattern += '%.1f+%.1fi'
print(pattern %(a1, b1, a2, b2, real, image) )
def printPatOfInput(real, image): # 得到输入数据的输出格式
if image < 0:
return '(%.1f%.1fi)'
else :
return '(%.1f+%.1fi)'
a1, b1, a2, b2 = input().split()
a1 = float(a1); b1 = float(b1); a2 = float(a2); b2 = float(b2)
tmp = complex(a1, b1) + complex(a2, b2)
printPatOfRes(printPatOfInput(a1, b1) + ' + ' + printPatOfInput(a2, b2) + ' = ', tmp.real, tmp.imag, a1, b1, a2, b2)
tmp = complex(a1, b1) - complex(a2, b2)
printPatOfRes(printPatOfInput(a1, b1) + ' - ' + printPatOfInput(a2, b2) + ' = ', tmp.real, tmp.imag, a1, b1, a2, b2)
tmp = complex(a1, b1) * complex(a2, b2)
printPatOfRes(printPatOfInput(a1, b1) + ' * ' + printPatOfInput(a2, b2) + ' = ', tmp.real, tmp.imag, a1, b1, a2, b2)
tmp = complex(a1, b1) / complex(a2, b2)
printPatOfRes(printPatOfInput(a1, b1) + ' / ' + printPatOfInput(a2, b2) + ' = ', tmp.real, tmp.imag, a1, b1, a2, b2)
参考
-
https://docs.python.org/3/library/functions.html#complex ↩
-
https://python3-cookbook.readthedocs.io/zh_CN/latest/c03/p06_complex_math.html ↩
-
https://www.zhihu.com/question/20221042 ↩
-
https://blog.csdn.net/yubai258/article/details/81330121 ↩