lua计算器不能正常工作

在我敲入+ - * 或 / 以外的任何字符时,它仍然会将所有的东西输出出来,只是最后会显示“无效”

print("+-*/?")
method = io.read()
if method == "+" or "-" or "*" or "/" then
  print("输入第一个数字")
  num1 = io.read()
  print("输入第二个数字")
  num2 = io.read()
elseif method ~= "+" or "-" or "*" or "/" then
  print("无效")
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
点赞
用户2858170
用户2858170

你的错误在下面这一行:

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

来源于 Lua 5.3 参考手册 3.4.5 逻辑运算符

在 Lua 中,逻辑运算符包括 and、or 和 not。就像控制结构一样(见 §3.3.4),所有逻辑运算符都会将 false 和 nil 视为 false,而将其他任何值视为 true。

因此,无论 method 是什么,您 if 语句的条件都将始终计算为 true,因为您正在 or 至少一个 true 值,这将导致 true

正如 Egor 已经提到的,您必须使用:

if method == "+" or method == "-" or method == "*" or method == "/" then
2018-04-23 18:22:14