//复数类
class complex {
var real:Int //实部
var virtual:Int//虚部
//指定构造器
init(real:Int,vir:Int) {
self.real = real
virtual = vir
}
//打印
func show() ->Void{
if real==0{
if virtual==0{
print(0)
}
else{
print("\(virtual)i")
}
}
else{
if virtual==0{
print(real)
}
else if virtual>0{
print("\(real)+\(virtual)i")
}
else{
print("\(real)\(virtual)i")
}
}
}
//加法
func add(other:complex) ->complex{
let sum:complex=complex(real:self.real + other.real, vir:self.virtual + other.virtual)
return sum
}
//乘法
func mul(other:complex) ->complex{
var newReal = self.real * other.real-self.virtual * other.virtual
var newVir = self.real * other.virtual+self.virtual * other.real
return complex(real: newReal, vir: newVir)
}
}
var com1 = complex(real:0, vir:0)
com1.show()
var com2 = complex(real:0, vir:2)
com2.show()
var com3 = complex(real:0, vir:-3)
com3.show()
var com4 = complex(real:6, vir:0)
com4.show()
var com5 = complex(real:6, vir:-2)
com5.show()
var com6 = complex(real:6, vir:5)
com6.show()
//加法的调用
var res = com5.add(other:com6)
res.show()
//乘法的调用
var res1 = com5.mul(other:com6)
res1.show()
网友评论