【问题标题】:repeat until loop in lua重复直到在lua中循环
【发布时间】:2018-03-01 04:05:51
【问题描述】:

我的 lua 代码做错了什么?

local which

print("Type f to convert fahrenheit to celsius and c to convert celsius to fahrenheit")
which = io.read()
repeat
    if which=="f" then
        local c
        local f
        print("input your fahrenheit temperature")
        f = tonumber(io.read())
        c = (f-32)/1.8
        print(c)
    end

    elseif which=="c" then
        local ce
        local fa
        print("input your celsius temperature")
        c = tonumber(io.read())
        f = (c*1.8)+32
    end

    else do
    print("Type f to convert fahrenhiet to celsius and c to convert celsius to fahrenheit")
until which=="f" or which=="c"

【问题讨论】:

  • 保持一致的缩进让事情更清晰:缩进你的重复主体......这将帮助你解决很多此类错误(尽管不完全是这种情况)。

标签: lua


【解决方案1】:

您将首先关闭您的 if 块。删除用于关闭ifelseifend 语句,并将其放在else 之后。

local which

print("Type f to convert fahrenheit to celsius and c to convert celsius to fahrenheit")
which = io.read()
repeat
    if which=="f" then
        local c
        local f
        print("input your fahrenheit temperature")
        f = tonumber(io.read())
        c = (f-32)/1.8
        print(c)

    elseif which=="c" then
        local ce
        local fa
        print("input your celsius temperature")
        c = tonumber(io.read())
        f = (c*1.8)+32

    else
        print("Type f to convert fahrenhiet to celsius and c to convert celsius to fahrenheit")
    end
until which=="f" or which=="c"

P.S.:这可能会导致您陷入无限循环。您需要在重复直到每次迭代后更新which

【讨论】:

    【解决方案2】:

    elseif 之前不应有end。在else 之前也应该没有end,在else 之后也应该没有do。在else 部分之后和until 之前应该有一个end

    repeat
      if ... then
        ...
      elseif ... then
        ...
      else
        ...
      end
    until ...
    

    如果您至少发布您的问题是什么(错误消息、意外输出等),下次会有所帮助。

    【讨论】:

      【解决方案3】:
      local which
      repeat
          print("Type f to convert fahrenheit to celsius and c to convert celsius to fahrenheit")
          which = io.read()
          if which=="f" then
              local c
              local f
              print("input your fahrenheit temperature")
              f = tonumber(io.read())
              c = (f-32)/1.8
              print(c)
      
          elseif which=="c" then
              local c
              local f
              print("input your celsius temperature")
              c = tonumber(io.read())
              f = (c*1.8)+32
              print(f)
          end
          print("do you want to play again? y/n?")
          antwort = io.read()
      
      
      until antwort ~= "y"
      

      【讨论】:

      • 你能简单描述一下是什么问题吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 2010-11-07
      • 2017-11-13
      • 2022-06-30
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多