减法中的角测试用例场景

2024-09-24 02:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python中的OOP概念。我遇到了一个挑战,我们需要创建一个对象“comp”来执行复数的加减运算。但是我得到了两个角落案例测试场景,对于我编写的代码,它们都失败了

class comp:

def __init__(self, Real, Imaginary=0.0):

    self.Real = Real
    self.Imaginary = Imaginary
    
def add(self,other):
    a=self.Real
    b=self.Imaginary
    c=other.Real
    d=other.Imaginary
    rsum=(a+c)
    isum=(b+d)
    print('Sum of the two Complex numbers :{}+{}i'.format(rsum,isum))
    #logging.debug('Sum of the two Complex numbers :{}+{}i'.format(rsum,isum))
    return('Sum of the two Complex numbers :{}+{}i'.format(rsum,isum))
    

def sub(self,other):
    a=self.Real
    b=self.Imaginary
    c=other.Real
    d=other.Imaginary
    rsub=(a-c)
    isub=(b-d)
    print('Subtraction of the two Complex numbers :{}+{}i'.format((rsub),(isub)))
    return('Subtraction of the two Complex numbers :{}+{}i'.format((rsub),(isub)))

两个失败的输出为:

  1. 两个复数之和:4+6i

两个复数的减法:-2+-2i

2)两个复数之和:6+9i

两个复数的减法:-6+-9i

我找不到如何让代码处理所有的角落案例场景。非常感谢您在这方面的任何帮助

提前谢谢


Tags: oftheselfformatdefreal复数sum
1条回答
网友
1楼 · 发布于 2024-09-24 02:25:59

我通过阅读StackOverflow中的内置类型文档和其他答案,了解了如何转换符号。 涵盖角落场景的工作代码:

class comp:

def __init__(self, Real, Imaginary=0.0):

    self.Real = Real
    self.Imaginary = Imaginary
    
def add(self,other):
    a=self.Real
    b=self.Imaginary
    c=other.Real
    d=other.Imaginary
    rsum=(a+c)
    isum=(b+d)
    
    print('Sum of the two Complex numbers :%d+%di' % (rsum,isum))
    return('Sum of the two Complex numbers :%d+%di' % (rsum,isum ))
    #return (rsum+isum)

def sub(self,other):
    a=self.Real
    b=self.Imaginary
    c=other.Real
    d=other.Imaginary
    rsub=((a)-(c))
    isub=((b)-(d))
    
    print('Subtraction of the two Complex numbers :%d%+di' % (rsub,+(isub)))
    return('Subtraction of the two Complex numbers :%d%+di' % (rsub,+(isub)))

相关问题 更多 >