2014-04-14 88 views
0

我正在製作一個小程序,用戶輸入一個數字並且程序生成一個隨機數。但是程序只是在用戶輸入一個數字後立即停止。我不知道是什麼導致了這一點。希望這裏有人可以幫助我解決這個問題,我對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 = 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 
+3

你沒有提到程序是如何退出的,我假設這是因爲你試圖將一個字符串與一個數字進行比較。這可能會幫助你閱讀你想要的類型:http://stackoverflow.com/questions/12069109/getting-input-from-the-user-in-lua –

+0

在我的系統上它不會停止,它會失敗錯誤消息,它沒有在你的系統上做到這一點? – Schollii

回答

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 
+0

'io.read'* n''可以創造奇蹟:-) – hjpotter92

+0

@ hjpotter92結果是相同的,無論是數字還是零。我按照我認爲可能不那麼令人困惑的方式行事,但我確實通過回答解釋了'* n'等上面的問題。 –

+0

@Retired忍者因此,只是爲了得到這個直接io.read()不能用於得到一個整數的輸入。它必須放在tonumber()中爲什麼?當我打印出numGuess的結果時,它仍然是一個整數。也是使用重複更好的這種情況而不是一個while循環?因爲那是我遇到節目結束的問題。 – carlos