|
发表于 2023-10-6 17:12:55
|
显示全部楼层
为了实现你想要的输出格式,你可以在 __str__ 方法中添加一个条件判断,以便在虚部为负数时显示减号。以下是修改后的 __str__ 方法:
- def __str__(self):
- sign = '+' if self.imag >= 0 else '-'
- return f'{self.real:.2f} {sign} {abs(self.imag):.2f}i'
复制代码
现在,当虚部为负数时,输出将显示减号。这是修改后的完整代码:
- class ComplexNumber:
- def __init__(self, real, imag):
- self.real = real
- self.imag = imag
- def __add__(self, other):
- return ComplexNumber(self.real + other.real, self.imag + other.imag)
- def __sub__(self, other):
- return ComplexNumber(self.real - other.real, self.imag - other.imag)
- def __mul__(self, other):
- real_part = self.real * other.real - self.imag * other.imag
- imag_part = self.real * other.imag + self.imag * other.real
- return ComplexNumber(real_part, imag_part)
- def __truediv__(self, other):
- denominator = other.real[b]2 + other.imag[/b]2
- real_part = (self.real * other.real + self.imag * other.imag) / denominator
- imag_part = (self.imag * other.real - self.real * other.imag) / denominator
- return ComplexNumber(real_part, imag_part)
- def __str__(self):
- sign = '+' if self.imag >= 0 else '-'
- return f'{self.real:.2f} {sign} {abs(self.imag):.2f}i'
- # Example usage
- c1 = ComplexNumber(1, 2)
- c2 = ComplexNumber(3, -4)
- print(c1 + c2) # Output: '4.00 - 2.00i'
- print(c1 - c2) # Output: '-2.00 + 6.00i'
- print(c1 * c2) # Output: '11.00 + 2.00i'
- print(c1 / c2) # Output: '-0.20 + 0.40i'
复制代码
现在,你应该得到了期望的输出结果:
- 4.00 - 2.00i
- ·2.00 + 6.00i
- 11.00 + 2.00i
- ·0.20 + 0.40i
复制代码
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案 |
|