Lua的elseif无法正常工作。

当我尝试使用elseif时,它不起作用。在下面的代码中,无论用户输入哪个数字,只有在if语句下运行的代码。

io.write("您想把摄氏度转换为华氏度(1),还是反过来(2)?")
pref = io.read()
if pref == 1 then
  io.write("你好! 你的摄氏度是多少?")
  local cel = io.read()
  far = (cel * 1.8 + 32)
  io.write("那个华氏度的温度是:" .. far)
elseif pref == 2 then
  io.write("你好! 你的华氏度是多少?")
  local far = io.read()
  cel = ((far - 32) / 1.8)
  print("那个摄氏度的温度是:" .. cel)
end
点赞
用户1009479
用户1009479

问题不是在于 elseif 这一部分。问题是因为 io.read() 返回的是一个字符串。要么将其转换为数字:

pref = tonumber(io.read())

或者,将 pref"1""2" 进行比较。

2015-07-04 19:17:36