import Foundation
class Complex {
var real = 0 // 实部
var virtual = 0 // 虚部
func add(other:Complex)->Complex{
let sum:Complex = Complex()
sum.real = self.real + other.real
sum.virtual = self.virtual + other.virtual
return sum
}
func minus(other:Complex) ->Complex{
let sum:Complex = Complex()
sum.real = self.real - other.real
sum.virtual = self.virtual - other.virtual
return sum
}
func ride(other:Complex) ->Complex{
let sum:Complex = Complex()
sum.real = self.real * other.real - self.virtual * other.virtual
sum.virtual = self.real * other.virtual + self.virtual * other.real
return sum
}
func show() {
if real != 0 {
if virtual > 0 {
print("\(real)+\(virtual)i")
}else if virtual < 0{
print("\(real)\(virtual)i")
}else{
print("\(real)")
}
}
else{
if virtual != 0 {
print("\(virtual)i")
}else{
print("0")
}
}
}
}
var com = Complex()
com.real = 17
com.virtual = -6
com.show()
var com2 = Complex()
com2.real = -8
com2.virtual = 9
com2.show()
var sum = com.add(other: com2)
sum.show()
var sum1 = com.minus(other: com2)
sum1.show()
var sum2 = com.ride(other: com2)
sum2.show()
Swift_复数类
最新推荐文章于 2024-08-15 22:18:46 发布