程序过早结束,可能与Lua有关。

我正在制作一个小程序,用户输入一个数字,程序会生成一个随机数。但是程序在用户输入数字后就立即停止了。我不知道是什么原因。希望这里有人能帮我解决这个问题,我是 Lua 和编程方面的新手。

print("你想玩一个游戏吗?")
playerInput = io.read()

if playerInput == "是" then
    print("你的数字是多少?")
    numGuess = io.read()

    rad = math.random(0, 100)

    while numGuess ~= rad do
        if numGuess < rad then
            print("太低了")
        elseif numGuess > rad then
            print("太高了")
        else
            print("你猜对了")
        end

        print("你的数字是多少?")
        numGuess = io.read()
    end

else
    print("你怕了吗?")
end
点赞
用户920069
用户920069

你可以尝试这样做:

-- 使用当前时间作为随机数生成器的种子,以便每次选择的数字都不同
math.randomseed(os.time())
rad = math.random(100)
--print("rad = " .. rad)

print("要玩一局游戏吗?")
playerInput = io.read()

if playerInput == "yes" then
  repeat
    print("猜一个数是多少?")
    numGuess = tonumber(io.read())
    if numGuess < rad then
      print("太小了")
    elseif numGuess > rad then
      print("太大了")
    else
      print("你猜对了")
    end
  until numGuess == rad
else
  print("怕了吗?")
end

我添加了随机数生成器的种子,否则,选择的数字在我的情况下总是0。我还重新排列了你的循环,以避免重复。

我认为你遇到的主要问题是比较数值和字符串,为了避免这种情况,我使用了 tonumber 函数将读取的值转换为数字。如果输入的不是数字,这仍然会导致崩溃,因此在实际程序中,你需要添加一些错误检查。

这是另一种使用while循环而不是repeat和 io.read('* n') 而不是 tonumber() 的版本。我将提示移到循环的顶部,以便在你猜对数字之后,程序仍然会执行,否则循环会在不再满足条件的情况下退出,而不输出任何内容。

math.randomseed(os.time())
print("要玩一局游戏吗?")
playerInput = io.read()

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

    while numGuess ~= rad do
        print("猜一个数是多少?")
        numGuess = io.read('*n')

        if numGuess < rad then
            print("太小了")
        elseif numGuess > rad then
            print("太大了")
        else
            print("你猜对了")
        end
    end
else
    print("怕了吗?")
end
2014-04-14 03:41:10