Lua 复数计算器

Lua复数计算器

主要包括复数的加减乘除操作,以及打印

编写复数类

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

代码调用

lua 复制代码
-- ***** 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))
相关推荐
散峰而望几秒前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
4***149013 分钟前
C++在系统中的编译优化
开发语言·c++
田姐姐tmner15 分钟前
Python切片
开发语言·python
oioihoii19 分钟前
C++程序执行起点不是main:颠覆你认知的真相
开发语言·c++
周杰伦fans1 小时前
C# 中的**享元工厂**模式
开发语言·数据库·c#
u***u6851 小时前
C++在系统中的异常处理
java·开发语言·c++
爱学测试的雨果1 小时前
收藏!软件测试面试题
开发语言·面试·职场和发展
安然无虞1 小时前
JMeter性能测试工具·下
开发语言·测试工具·jmeter
4***R2401 小时前
C++在音视频处理中的库
开发语言·c++·音视频
embrace992 小时前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程