2012-06-18 30 views
2

,直到我想編寫一個if語句,將繼續重複一個問題,直到滿足特定條件重複在函數中前行的if語句滿足

事情是這樣的:

fun<-function(){ 
    x<-readline("what is x? ") 
    if(x>5) 
    {print("X must be less than 5") 
    **repeat lines 3 & 4** 
}else{ 
    print("Correct")} 

} 

對不起** - 但我不確定如何正確寫入該行。我期望做的是在每次輸入大於5的數字時重複提示「什麼是x」,直到給出小於5的數字。理論上這個函數看起來像這樣

fun() 
what is x? 6 
X must be less than 5 
what is x? 8 
X must be less than 5 
what is x? 3 
Correct 
+0

'while'這樣做。 – Justin

回答

5

readline返回一個特徵向量,所以你需要將它強制爲數字在if之前。然後你可以使用while循環(正如其他人指出的那樣)。

fun <- function() { 
    x <- as.numeric(readline("what is x? ")) 
    if(is.na(x)) stop("x must be a number") 
    while(x > 5) { 
    print("X must be less than 5") 
    x <- as.numeric(readline("what is x? ")) 
    if(is.na(x)) stop("x must be a number") 
    } 
    print("Correct") 
} 
6

我不太確定你使用的語言,但是像while循環這樣的東西應該這樣做。

fun<-function(){ 
    x<-readline("what is x? ") 
    while(x>5) 
    { 
    print("X must be less than 5") 
    x<-readline("what is x? ") 
    } 
    print("Correct")} 
} 
+0

+1爲了正確地寫一個你不知道的語言的'while'循環。 – joran

+0

很棒的猜測,但'readline'返回一個字符串,這使得邏輯比較失敗。 –

4

您可以使用控制結構while此:

continue <- FALSE 

while(!continue){ 
x<-readline("what is x? ") 
    if(x>5){ 
    print("X must be less than 5") 
    } else { 
    continue <- TRUE 
    print("Correct") 
    } 
} 

有關更多詳細信息,請參閱?"while"?Control

4

其他人還提到while,你也可以使用repeatif滿足調用break。這可以用來創建其他語言稱爲「直到」循環的內容。

這種感覺更像是問什麼問題,而不是while選項(但它主要只是一種不同的語法特徵,兩者最終都會以編程方式相同)。