首页 > 解决方案 > 与 Lua 编程相关的帮助,其中 Basic Calculator 需要使用 3 个运算符加法、减法和乘法构建

问题描述

我们给出了以下任务

使用 Lua 创建三个可以执行加法、减法和乘法的函数/

程序应该是

接受任何数字。检查运算符 + - *。如果不是打印“无效操作数”并退出。接受两个操作数。如果任何操作数不是数字,则打印“无效操作数”并退出。使用 -tonumber() 执行操作并打印结果。

我们编写了如下代码,但没有按预期工作,不知道哪里出错了,请指导我们

local operators = {
    ["+"] = function(x,y) return x+y end,
    ["-"] = function(x,y) return x-y end,
    ["*"] = function(x,y) return x*y end
}

local function default()
    print "Invalid operand"
end

local num1 = io.read()
local num2 = io.read()
local operator = io.read()

local func (
 if operator == "+" then
   local add = tonumber(num1) + tonumber(num2)   
 end 
 if operator == "-" then
   local subtract = tonumber(num1) - tonumber(num2)
 end
 if operator == "*" then
   local multiply = tonumber(num1) * tonumber(num2)
 end
)
or default
print(func(num1,num2))
io.read()

正确的代码是

local operators = {
  ["+"] = function (x, y) return x + y end,
  ["-"] = function (x, y) return x - y end,
  ["*"] = function (x, y) return x * y end,
}

local operator = operators[io.read()]
local num1 = tonumber(io.read())
local num2 = tonumber(io.read())

if num1 and num2 then
  if operator then
    print(operator(num1, num2))
  else
    print("Invalid operator")
  end
else
  print("Invalid operand")
end

标签: lua

解决方案


您的代码有语法错误,没有太大意义。

local func (
 if operator == "+" then
   local add = tonumber(num1) + tonumber(num2)   
 end 
 if operator == "-" then
   local subtract = tonumber(num1) - tonumber(num2)
 end
 if operator == "*" then
   local multiply = tonumber(num1) * tonumber(num2)
 end
)
or default

要定义本地函数,您可以编写

local myFunction = function() end

或者

local function myFunction() end

但不是

local func()

当您定义函数时,它永远不能为零。所以短路一个函数定义,比如

local default = function() end
local myFunction = function() end or default

没有意义。

您应该添加说明,以便用户知道在您调用 io.read() 之前要输入什么。

您的这部分代码根本没有使用:

local operators = {
    ["+"] = function(x,y) return x+y end,
    ["-"] = function(x,y) return x-y end,
    ["*"] = function(x,y) return x*y end
}

此外,您的函数func除了创建未使用的局部变量外什么也不做。

该函数不返回值,因此打印它的返回值print(func(num1, num2))不会按预期打印结果。

您也无法检查用户是否实际输入了有效字符,例如数字或运算符。如果用户输入其他内容,这将导致 Lua 错误。


推荐阅读