2017-08-29 109 views
0

我在製作猜謎遊戲時遇到了正確的括號語法問題。這裏是我的代碼一個簡單的例子R猜謎遊戲的語法

number_result <- readline(prompt = "Choose a number btwn 1 & 100: ") 
input <- 0 
rand <- sample(seq(1,100), size = 1) 

input = number_result 


while(input != rand){ 

    if(input < rand){ 
    print("Higher!") 
    } 
    else if(input > rand){ 
    print("Lower!") 
    } 
    else(input = rand){ 
    return(print("You got it!")) 
} 
    } 

我的錯誤是:

Error: unexpected '{' in: 
" } 
    else(input = rand){" 
>  return(print("You got it!")) 
[1] "You got it!" 
Error: no function to return from, jumping to top level 
> } 
Error: unexpected '}' in "}" 
>  } 
Error: unexpected '}' in " }" 
> 
+1

你的意思是說你的第三條'else'語句有條件嗎?如果是這樣,則使用'else if',如果不是,則使用'else {'並且不需要包含'(input = rand)'部分。另外,__'R'__使用double等於'=='進行邏輯等式檢查,而不是單個等於'=',因爲您輸入了。只要輸入'print('You got it!')'''''''''''''沒有'return'包裝 – bouncyball

+0

謝謝,我認爲邏輯相等「==」是最大的東西 - 我仍然使用return儘管結束while循環。我想我會創建一個返回的函數,直到用戶能夠正確猜測數字爲止。 – SamGROW

回答

-2

沒有回報,因爲你沒有定義一個函數需要。您還必須指定一個停止條件!否則,你的時間將永遠運行。 試試這個

 number_result <- readline(prompt = "Choose a number btwn 1 & 100: ") 
     input <- 0 
     rand <- sample(seq(1,100), size = 1) 

     input = number_result 
while(input != rand){ 
    if(input < rand){ 
    print("Higher!") 
    } else if(input > rand){ 
    print("Lower!") 
    } else { 
    print("You got it!") 
    } 
    input <- input + 1 
} 
+0

有一個更嚴重的基本問題,你錯過了 – bouncyball

+0

是的你是對的!剛剛編輯;) –

+0

OP也想要一個'while'循環 – bouncyball