Python 如何正确打印输出__
如何正确打印输出strPython 如何正确打印输出__,python,string,Python,String,如何正确打印输出str class Complex(object): def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __add__(self, other): return Complex(self.real+other.real, self.imaginary+other.imaginary) d
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return Complex(self.real+other.real, self.imaginary+other.imaginary)
def __sub__(self, other):
return Complex(self.real-other.real, self.imaginary-other.imaginary)
def __str__(self):
return '{} & {}i'.format(self.real, self.imaginary)
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
#print (x)
y = Complex(*d)
#print (y)
print(*map(str, [x+y, x-y]), sep='\n')
输入
21
5.6
输出
7.0和7.0i
-3.0和-5.0i
如果加法应打印+而减法应打印,则预期输出-
7.00+7.00i
-3.00-5.00i
在您的str实现中使用此选项
def __str__(self):
return f"{self.real}{ '+' if self.imaginary >= 0 else ''}{self.imaginary}i"
与此相反:
def __str__(self):
return '{} & {}i'.format(self.real, self.imaginary)
您可以这样做:
def __str__(self):
def __map_imaginary(imag):
if imag > 0:
return "+{:2f}i".format(imag)
if imag < 0:
return "{:2f}i".format(imag)
if imag == 0:
return ""
return "{}{}".format(self.real, __map_imaginary(self.imag))
def\uuuu str\uuuuuu(自):
定义映射(图像):
如果imag>0:
返回“+{:2f}i”。格式(imag)
如果imag<0:
返回“{:2f}i”。格式(imag)
如果imag==0:
返回“”
返回“{}{}”.format(self.real,uu-map\u-virtual(self.imag))
我假设你们不想打印虚部,若它等于0。你可以随意改变
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return Complex(self.real+other.real, self.imaginary+other.imaginary)
def __sub__(self, other):
return Complex(self.real-other.real, self.imaginary-other.imaginary)
def __str__(self):
return '{:.2f}{}{:.2f}i'.format(self.real, '+' if self.imaginary >= 0 else '', self.imaginary)
if __name__ == '__main__':
c = map(float, input().split())
d = map(float, input().split())
x = Complex(*c)
#print (x)
y = Complex(*d)
#print (y)
print(*map(str, [x+y, x-y]), sep='\n')
{.2f}
在这里,您可以阅读有关小数点精度的信息