Python真实与虚构:如何打印-2-2i
如果我没有得到想要的结果,请您帮助我使用以下代码:Python真实与虚构:如何打印-2-2i,python,python-3.x,add,subtraction,complex-numbers,Python,Python 3.x,Add,Subtraction,Complex Numbers,如果我没有得到想要的结果,请您帮助我使用以下代码: class comp: def __init__(self, real, imag): self.real=real self.imag=imag def add(self,other): print('Sum of the two Complex numbers :{}+{}i'.format(self.real+other.real,self.imag+other.im
class comp:
def __init__(self, real, imag):
self.real=real
self.imag=imag
def add(self,other):
print('Sum of the two Complex numbers :{}+{}i'.format(self.real+other.real,self.imag+other.imag))
def sub(self, other):
print('Subtraction of the two Complex numbers :{}+{}i'.format(self.real-other.real, self.imag-other.imag))
该代码可以工作,但当虚场的结果为-2时,我知道它会将结果打印为+-2i
结果
例如:1+2i-3+4i=-2-2i(但由于注释中硬编码为+,因此会产生-2+-2i)
帮助我理解如何摆脱它?我建议在每个函数中添加一个
if
语句。特别是if self.imag+other.imag<0:
用于添加。然后添加print的print
语句('两个复数之和:{}{}I'。格式(self real+other.real,self imag+other.imag))
。您还需要使用减法函数来完成此操作。此解决方案不会将函数保持在一行,但应该可以解决此问题。问题在于,您明确要求用加号分隔实部和虚部
这是一个简短的版本
class comp(复杂):
def添加(自身、其他):
打印(f'两个复数之和:{self+other}')
def接头(自身、其他):
打印(f'两个复数的减法:{self-other}')
x=成分(1,2)
y=comp(3,4)
x、 加(y)
#两个复数之和:(4+6j)
x、 分包(y)
#两个复数的减法:(-2-2j)
否则
def符号(x):
如果x>=0,则返回“+”,否则返回“”
班级薪酬:
定义初始化(自、实、imag):
真实的
self.imag=imag
def添加(自身、其他):
r=自实+其他实
i=self.imag+other.imag
print(两个复数之和:{r}{sign(i)}{i}i')
def接头(自身、其他):
r=self.real-other.real
i=self.imag-other.imag
print(两个复数的f'减法:{r}{sign(i)}{i}i')
x=成分(1,2)
y=comp(3,4)
x、 加(y)
#两个复数之和:4+6i
x、 分包(y)
#两个复数的减法:-2-2i
已经有了complex
。你为什么要重新发明轮子?print(complex(-2,-2));35;(-2-2j)
为什么您首先需要它?Python可以很好地处理复杂的数字。请确切地解释您是如何被困在这一点上的。您特意让代码只打印+
。如果您坚持构建自己的机制来打印复杂的数字,那么您需要测试问题案例并处理它魔鬼代言人:这看起来像是OOP实践。