我想最好的办法就是这样x = (1.542334+32.5322j)
x = complex(round(x.real),round(x.imag))
如果你不想每次都重复,你可以把它放到一个函数中。在
^{pr2}$
然后可以添加其他可选参数,例如,如果您只想取整一个部分,或者如果您只想将实数部分或复杂部分四舍五入到小数位数def round_complex(x, PlacesReal = 0, PlacesImag = 0, RoundImag = True, RoundReal = True):
if RoundImag and not RoundReal:
return complex(x.real,round(x.imag,PlacesImag))
elif RoundReal and not RoundImag:
return complex(round(x.real,PlacesReal),x.imag)
else: #it would be a waste of space to make it do nothing if you set both to false, so it instead does what it would if both were true
return complex(round(x.real,PlacesReal),round(x.imag,PlacesImag))
由于变量自动设置为true或0,因此除非您特别需要,否则不需要输入它们。但它们很方便