我正在制作一个用户输入数字的小程序,程序会生成一个随机数。但是程序在用户输入数字后立即停止。我不知道造成这种情况的原因。希望有人在这里可以帮助我解决这个问题,我是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
答案 0 :(得分: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