lua 计算器无法正常工作
lua calculator not working properly
当我输入除 + - * 或 / 以外的其他内容时,它仍然只在最后打印出所有内容,它说 "invalid"
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
你的错误在下面一行:
if method == "+" or "-" or "*" or "/" then
来自Lua 5.3 Reference Manual 3.4.5 Logical Operators
The logical operators in Lua are and, or, and not. Like the control
structures (see §3.3.4), all logical operators consider both false and
nil as false and anything else as true.
因此,无论使用何种方法,您的 if 语句的条件将始终评估为 true
,因为您 or
至少有一个 true
值,结果为 true
.
正如 Egor 已经提到的,您必须使用:
if method == "+" or method == "-" or method == "*" or method == "/" then
当我输入除 + - * 或 / 以外的其他内容时,它仍然只在最后打印出所有内容,它说 "invalid"
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
你的错误在下面一行:
if method == "+" or "-" or "*" or "/" then
来自Lua 5.3 Reference Manual 3.4.5 Logical Operators
The logical operators in Lua are and, or, and not. Like the control structures (see §3.3.4), all logical operators consider both false and nil as false and anything else as true.
因此,无论使用何种方法,您的 if 语句的条件将始终评估为 true
,因为您 or
至少有一个 true
值,结果为 true
.
正如 Egor 已经提到的,您必须使用:
if method == "+" or method == "-" or method == "*" or method == "/" then