Lua复数计算器
主要包括复数的加减乘除操作,以及打印
编写复数类
-- ***** 元类 *****
Complex = {real = 0, imag = 0}
-- 构造函数
function Complex:new(real, imag)
local o = o or {}
o.real = real or 0
o.imag = imag or 0
setmetatable(o, self)
self.__index = self
return o
end
-- 重载加法运算符
function Complex:__add(c2)
local o = Complex:new()
o.real = self.real + c2.real
o.imag = self.imag + c2.imag
--print(o.real, o.imag)
return o
end
-- 重载减法运算符
function Complex:__sub(c2)
local o = Complex:new()
o.real = self.real - c2.real
o.imag = self.imag - c2.imag
return o
end
-- 重载乘法运算符
function Complex:__mul(c2)
local o = Complex:new()
o.real = self.real * c2.real - self.imag * c2.imag
o.imag = self.imag * c2.real + self.real * c2.imag
return 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 o
end
-- 使用tostring修改打印信息
function Complex:__tostring()
real = self.real or 0
imag = self.imag or 0
if real == 0 then
if imag ~= 0 then
return imag..'i'
else
return real
end
elseif imag == 0 then
return real..''
else
return real .. '' .. imag..'i'
end
end
return 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))