【问题标题】:Program ending to soon with lua程序即将用 lua 结束
【发布时间】:2014-04-15 09:47:41
【问题描述】:

我正在制作一个小程序,用户输入一个数字,程序会生成一个随机数。但是程序会在用户输入数字后立即停止。我不知道是什么原因造成的。希望这里有人可以帮助我解决这个问题,我是 lua 新手并自己编程。

print("Do you want to play a game?")
playerInput = io.read()

if playerInput == "yes" then
    print("What is your number?")
    numGuess = io.read()

    rad = math.random(0,100)

    while numGuess ~= rad do
        if numGuess < rad then
            print("To low")
        elseif numGuess > rad then
            print("to high")
        else 
            print("You got the number")
        end

        print("What is your number?")
        numGuess = io.read()
    end

else
    print("You scared?")
end

【问题讨论】:

  • 您没有提到程序是如何退出的,我认为这是因为您试图将字符串与数字进行比较。这可能会帮助您阅读所需的类型:stackoverflow.com/questions/12069109/…
  • 在我的系统上它不只是停止,它失败并显示错误消息,你的系统上没有这样做吗?

标签: lua


【解决方案1】:

你可以试试这样的:

-- Seed the random number generator with the current time
-- so the number chosen is not the same every time
math.randomseed(os.time())
rad = math.random(100)
--print("rad = " .. rad)

print("Do you want to play a game?")
playerInput = io.read()

if playerInput == "yes" then
  repeat
    print("What is your number?")
    numGuess = tonumber(io.read())
    if numGuess < rad then
      print("Too low")
    elseif numGuess > rad then
      print("Too high")
    else
      print("You got the number")
    end
  until numGuess == rad
else
  print("You scared?")
end

我添加了随机数生成器的种子,否则选择的数字对我来说始终为 0。我还重新安排了你的循环以避免重复。

我认为您遇到的主要问题是将数字与字符串进行比较,以避免我使用 tonumber 函数将读取的值转换为数字。如果输入除数字以外的任何内容,这仍然会崩溃,因此在实际程序中您需要添加一些错误检查。

这是一个使用 while 循环而不是重复和 io.read('*n') 而不是 tonumber() 的版本。我将提示移到循环的顶部,以便在您猜到正确的数字后执行主体,否则循环将退出而不打印任何内容,因为循环条件不再为真。

math.randomseed(os.time())
print("Do you want to play a game?")
playerInput = io.read()

if playerInput == "yes" then
    local numGuess = 999
    local rad = math.random(0,100)

    while numGuess ~= rad do
        print("What is your number?")
        numGuess = io.read('*n')

        if numGuess < rad then
            print("To low")
        elseif numGuess > rad then
            print("to high")
        else 
            print("You got the number")
        end
    end
else
    print("You scared?")
end

【讨论】:

  • @hjpotter92 结果都是一样的,无论是数字还是零。我选择了我认为可能不那么令人困惑的内容,但我确实链接到另一个问题的答案,上面解释了“* n”等。
  • @Retired Ninja 因此,不能直接使用 io.read() 来获取整数的输入。它必须放在 tonumber() 里面,这是为什么?当我打印出 numGuess 的结果时,它仍然是一个整数。在这种情况下使用重复比使用while循环更好吗?因为那是我遇到程序结束问题的地方。
  • 我添加了一个额外的示例,保留while 循环并使用io.read('*n') 读取数字。 io.read() 将始终返回一个字符串,除非您使用 '*n' 参数。您可以在documentation 中阅读更多相关信息。
猜你喜欢
  • 2011-04-24
  • 1970-01-01
  • 2018-01-27
  • 2011-04-18
  • 2010-10-26
  • 2019-05-28
  • 1970-01-01
  • 2014-03-18
  • 2021-11-11
相关资源
最近更新 更多