Lua 实现复数计算器
要求:实现一个Complex复数结构,支持复数的加、减、乘、除四则运算
主要思路:利用元表,通过元方法重写四则运算操作符
方法1:通过元表实现
-- ***** 元表 *****
metaTable = {}
-- a+bi, c+di
-- c1[1], c1[2], c2[1], c2[2]
-- 使用元表的元方法 更改加减乘除对应运算符的操作
function metaTable.__add(c1, c2)
res = {}
res[1] = c1[1] + c2[1]
res[2] = c1[2] + c2[2]
setmetatable(res, metaTable)
return res
end
function metaTable.__sub(c1, c2)
res = {}
res[1] = c1[1] - c2[1]
res[2] = c1[2] - c2[2]
setmetatable(res, metaTable)
return res
end
function metaTable.__mul(c1, c2)
res = {}
-- ac-bd, bc+ad i
res[1] = c1[1]*c2[1] - c1[2] * c2[2]
res[2] = c1[2]*c2[1] + c1[1] * c2[2]
setmetatable(res, metaTable)
return res
end
function metaTable.__div(c1, c2)
res = {}
--:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +((bc-ad)/(c^2+d^2))i
res[1] = (c1[1] * c2[1] + c1[2] * c2[2]) / (c2[1] * c2[1] + c2[2] * c2[2])
res[2] = (c1[2] * c2[1] - c1[1] * c2[2]) / (c2[1] * c2[1] + c2[2] * c2[2])
setmetatable(res, metaTable)
return res
end
-- 使用tostring修改打印信息
function metaTable.__tostring(mytable)
real = mytable[1] or 0
imag = mytable[2] 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
-- 复数函数
function Complex(a, b)
a = a or 0
b = b or 0
mytable = {a, b}
setmetatable(mytable, metaTable)
return mytable
end
local c1 = Complex(3.2, -5.1)
local c2 = Complex(7, 8)
local c3 = Complex(math.pi)
local c4 = Complex()
print((c1 + c4) * (c1 / c2 + c3))
-- output: 6.7653973764431-16.927609258972i
方法2:通过复数类实现
-- ***** 元类 *****
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
-- 创建实例对象
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))
-- output: 6.7653973764431-16.927609258972i