lua的节目即将结束
我正在制作一个小程序,用户输入一个数字,程序生成一个随机数。但程序在用户输入一个数字后立即停止。我不知道是什么原因造成的。希望这里有人能帮我解决这个问题,我是lua的新手,我自己编程lua的节目即将结束,lua,Lua,我正在制作一个小程序,用户输入一个数字,程序生成一个随机数。但程序在用户输入一个数字后立即停止。我不知道是什么原因造成的。希望这里有人能帮我解决这个问题,我是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
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
print(“您想玩游戏吗?”)
playerInput=io.read()
如果playerInput==“是”,则
打印(“您的号码是多少?”)
numGuess=io.read()
rad=数学随机数(0100)
而numGuess~=rad do
如果numGuessrad然后
打印(“至高”)
其他的
打印(“你得到了号码”)
结束
打印(“您的号码是多少?”)
numGuess=io.read()
结束
其他的
打印(“你害怕吗?”)
结束
您可以尝试以下方法:
-- 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
您没有提到程序是如何退出的,我想这是因为您试图将字符串与数字进行比较。这可能有助于您读取所需的类型:在我的系统上,它不会停止,它会失败并显示一条错误消息,它不是在您的系统上这样做的吗?@hjpotter92结果是相同的,一个数字或零。我选择了我认为不太容易混淆的问题,但我确实链接到了另一个问题,并给出了解释“*n”等的答案。@Retired Ninja,所以为了得到这个直接的io。read()不能用于获取整数的输入。必须把它放在桶里为什么?当我打印numGuess的结果时,它仍然是一个整数。对于这种情况,使用repeat是否比while循环更好?因为这就是程序结束的问题所在。我添加了另一个示例,使
while
循环,并使用io.read('*n')
读取数字io.read()
将始终返回字符串,除非使用'*n'
参数。你可以阅读更多关于这方面的文章。
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