lua计算器无法正常工作

时间:2018-04-23 16:35:36

标签: lua calculator

当我输入除+ - *或/之外的其他内容时,它仍然会打印出所有内容,但它最终会显示"无效"

print("+-*/?")
method = io.read()
if method == "+" or "-" or "*" or "/" then
  print("type a number")
  num1 = io.read()
  print("type another number")
  num2 = io.read()
elseif method ~= "+" or "-" or "*" or "/" then
  print("invalid")
end

if method == "+" then
  plusnum = num1 + num2
  print(plusnum)
elseif method == "-" then
  minusnum = num1 - num2
  print(minusnum)
elseif method == "*" then
  timesnum = num1 * num2
  print(timesnum)
elseif method == "/" then
  percentnum = num1 / num2
  print(percentnum)
end

1 个答案:

答案 0 :(得分:1)

你的错误在以下一行:

if method == "+" or "-" or "*" or "/" then

来自Lua 5.3 Reference Manual 3.4.5 Logical Operators

  

Lua中的逻辑运算符是和,或者是,而不是。像控件一样   结构(见§3.3.4),所有逻辑运算符都考虑 false和    nil as false 其他任何内容为true

因此,无论采用何种方法,if语句的条件将始终评估为true,因为您or至少有一个true值会导致{{1} }}

正如叶戈尔已经提到过你必须使用:

true