Lua复数计算器
主要包括复数的加减乘除操作,以及打印
编写复数类
-- ***** 元类 *****
Complex = {real = 0, imag = 0}-- 构造函数
function Complex:new(real, imag)local o = o or {}o.real = real or 0o.imag = imag or 0setmetatable(o, self)self.__index = selfreturn o
end-- 重载加法运算符
function Complex:__add(c2)local o = Complex:new()o.real = self.real + c2.realo.imag = self.imag + c2.imag--print(o.real, o.imag)return oend-- 重载减法运算符
function Complex:__sub(c2)local o = Complex:new()o.real = self.real - c2.realo.imag = self.imag - c2.imagreturn o
end-- 重载乘法运算符
function Complex:__mul(c2)local o = Complex:new()o.real = self.real * c2.real - self.imag * c2.imago.imag = self.imag * c2.real + self.real * c2.imagreturn o
end-- 重载除法运算符
function Complex:__div(c2)local o = Complex:new()o.real = (self.real * c2.real + self.imag * c2.imag) /(c2.real * c2.real + c2.imag * c2.imag)o.imag = (self.imag * c2.real - self.real * c2.imag) /(c2.real * c2.real + c2.imag * c2.imag)return oend-- 使用tostring修改打印信息
function Complex:__tostring()real = self.real or 0imag = self.imag or 0if real == 0 thenif imag ~= 0 thenreturn imag..'i'elsereturn realendelseif imag == 0 thenreturn real..''elsereturn real .. '' .. imag..'i'endendreturn Complex
代码调用
-- ***** Complex 四则运算 *****local Complex = require('Complex')local c1 = Complex:new(3.2, -5.1)local c2 = Complex:new(7, 8)local c3 = Complex:new(math.pi)local c4 = Complex:new()print((c1 + c4) * (c1 / c2 + c3))