一天三盒半 发表于 2026-5-25 17:57:08

Lua 入门教程——简单示例:计算器

-- 简单计算器程序
function calculator()
    print("=== Lua 计算器 ===")
    print("1. 加法")
    print("2. 减法")
    print("3. 乘法")
    print("4. 除法")
   
    io.write("请选择操作(1-4):")
    local choice = tonumber(io.read())
   
    io.write("请输入第一个数字:")
    local num1 = tonumber(io.read())
   
    io.write("请输入第二个数字:")
    local num2 = tonumber(io.read())
   
    local result
    if choice == 1 then
      result = num1 + num2
    elseif choice == 2 then
      result = num1 - num2
    elseif choice == 3 then
      result = num1 * num2
    elseif choice == 4 then
      if num2 == 0 then
            print("错误:除数不能为 0")
            return
      end
      result = num1 / num2
    else
      print("错误:无效的选择")
      return
    end
   
    print("结果:", result)
end

calculator()

lulu888 发表于 2026-5-25 23:55:15

:P:P:P:P:P:P:P
页: [1]
查看完整版本: Lua 入门教程——简单示例:计算器