下面是一个基于 Lua 的简单计算器的示例代码:

-- 计算器函数
function calculator()
    -- 读取用户输入
    io.write('请输入第一个数字:')
    local num1 = tonumber(io.read())
    
io.write('请输入运算符(+、-、*、/):')
    local operator = io.read()
    
io.write('请输入第二个数字:')
    local num2 = tonumber(io.read())
    
    -- 根据运算符进行计算
    local result = 0
    if operator == '+' then
        result = num1 + num2
    elseif operator == '-' then
        result = num1 - num2
    elseif operator == '*' then
        result = num1 * num2
    elseif operator == '/' then
        result = num1 / num2
    else
        print('无效的运算符')
        return
    end
    
    -- 输出结果
    print('计算结果:' .. result)
end

-- 调用计算器函数
calculator()

运行以上代码后,会提示用户输入两个数字和一个运算符,然后计算并输出结果。

Lua 简单计算器示例代码

原文地址: https://www.cveoy.top/t/topic/o1ZK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录