微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

复数的实现

如何解决复数的实现

我有这部分代码,我需要在类中实现或修改必要的方法,以便程序产生以下输出

client.commands.get('warn').execute(message,args)

表示复数的 Complex 类的实现缺失。显然,复数的属性是其实部和虚部(浮点数),不需要是受保护的属性。但我不知道如何实现它以获得上面的输出

到目前为止我所拥有的:

代码

c1 = 1+2i 
c2 = 3-4i 
c3 = -5 
c4 = 6i
c5 = -7i
c6 = 0
c1 + c2 = 4-2i
c1 - c2 = -2+6i
c1 * c2 = 11+2i 
conjugate of c1 = 1-2i

class Complex: def __init__(self,real,imag): self.real = real self.imag = imag def __str__(self): return str(self.real) + "+" + str(self.imag) + "i" def main(): c1 = Complex(1,2) print("c1 =",c1) c2 = Complex(3,-4) print("c2 =",c2) c3 = Complex(-5,0) print("c3 =",c3) c4 = Complex(0,6) print("c4 =",c4) c5 = Complex(0,-7) print("c5 =",c5) c6 = Complex(0,0) print("c6 =",c6) print("c1 + c2 =",c1 + c2) print("c1 - c2 =",c1 - c2) print("c1 * c2 =",c1 * c2) c7 = c1.conjugate() print("conjugate of c1 =",c7) if __name__ == "__main__": main() 无法更改

输出

def main()

解决方法

您可以使用内置的复数来实现这一点。与其他一些语言一样,Python 使用 j 作为虚数单位,而数学通常使用小写的 i

def main():
    c1 = 1+2j
    print("c1 =",c1)
    c2 = 3-4j
    print("c2 =",c2)
    c3 = -5+0j
    print("c3 =",c3)
    c4 = 0+6j
    print("c4 =",c4)
    c5 = 0-7j
    print("c5 =",c5)
    c6 = 0+0j
    print("c6 =",c6)
    print("c1 + c2 =",c1 + c2)
    print("c1 - c2 =",c1 - c2)
    print("c1 * c2 =",c1 * c2)
    c7 = c1.conjugate()
    print("conjugate of c1 =",c7)

if __name__ == "__main__":
    main()

给出输出:

c1 = (1+2j)
c2 = (3-4j)
c3 = (-5+0j)
c4 = 6j
c5 = -7j
c6 = 0j
c1 + c2 = (4-2j)
c1 - c2 = (-2+6j)
c1 * c2 = (11+2j)
conjugate of c1 = (1-2j)

如果您对附加括号没问题,那么您就完成了。否则,您可以进行输出格式设置,例如:

print(f"conjugate of c7 = {c7.real}{c7.imag:+}j")

编辑: 如果您的 main() 方法需要使用 Complex 类,您可以只包装内置函数:

class Complex(complex):
    pass

这是有效的,因为您的 Complex 类具有与内置 complex 数据类型相同的原型。您甚至可以按照您的建议重载 __str__(self),只要请求 str(),它就可以工作。因此 Complex 类可能如下所示:

class Complex(complex):
    def __str__(self):
        return str(self.real) + "+" + str(self.imag) + "i"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。