基本的Lua Loop不能正常工作

时间:2013-12-05 12:16:21

标签: lua

所以基本上我有这个计算器,您可以在除法,乘法,加号和减号之间进行选择。我刚刚学会了如何循环程序。但循环不能正常工作。

print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")

restart = 1

x = tonumber(io.read())

while restart == 1 do

if x == 1 then
    print("Please write the first number to add up")
    n1 = tonumber(io.read())
    print("Please write the second number to add up")
    n2 = tonumber(io.read())
    print(n1 .. "+" .. n2 .. "=" .. n1+n2)
elseif x == 2 then
    print("Please write the first number to subtract")
    n1 = tonumber(io.read())
    print("Please write the second number to subtract")
    n2 = tonumber(io.read())
    print(n1 .. "-" .. n2 .. "=" .. n1-n2)
elseif x == 3 then
    restart = 0
    print("Please write the first number to divide")
    n1 = tonumber(io.read())
    print("Please write the second number to divide")
    n2 = tonumber(io.read())
    print(n1 .. "/" .. n2 .. "=" .. n1/n2)
elseif x == 4 then
    print("Please write the first number to multiply")
    n1 = tonumber(io.read())
    print("Please write the second number to multiply")
    n2 = tonumber(io.read())
    print(n1 .. "*" .. n2 .. "=" .. n1*n2)
end
end

所以发生的事情基本上是你选择减去然后你输入让我们说10-2。它的工作原理应该如此。但问题是只有负部分保持循环。它并没有要求你选择一种繁殖方式。我该如何解决这个问题?

E.g我希望你能为你做这个等式,然后循环回到开头。

3 个答案:

答案 0 :(得分:2)

你可以替换它:

print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")

restart = 1

x = tonumber(io.read())

while restart == 1 do

由此:

restart = 1

while restart == 1 do

print("Please choose the way to use the calculator")
print("[1] Plus [2] Minus [3] Division [4] Multiply")

x = tonumber(io.read())

另一方面,由于您正在学习Lua,因此您可以通过以下方式重构此代码(正确使用本地等):

local get_operands = function(s)
  print("Please write the first number to " .. s)
  local n1 = io.read("*n")
  print("Please write the second number to " .. s)
  local n2 = io.read("*n")
  return n1, n2
end

while true do

  print("Please choose the way to use the calculator")
  print("[1] Plus [2] Minus [3] Division [4] Multiply")

  local x = io.read("*n")

  if x == 1 then
      local n1, n2 = get_operands("add up")
      print(n1 .. "+" .. n2 .. "=" .. n1+n2)
  elseif x == 2 then
      local n1, n2 = get_operands("subtract")
      print(n1 .. "-" .. n2 .. "=" .. n1-n2)
  elseif x == 3 then
      local n1, n2 = get_operands("divide")
      print(n1 .. "/" .. n2 .. "=" .. n1/n2)
      break
  elseif x == 4 then
      local n1, n2 = get_operands("multiply")
      print(n1 .. "*" .. n2 .. "=" .. n1*n2)
  end

end

答案 1 :(得分:1)

你不需要把输入放在循环中吗?

x = tonumber(io.read())

while restart == 1 do

应该是

while restart == 1 do

x = tonumber(io.read())

答案 2 :(得分:0)

你在循环外面设置x,所以它永远不会改变。将x =输入放在循环中,这样每次迭代都会重新读取。