当我的while循环随机工作时,我很困惑?
how.many<-function(fruit, number){
string<-paste("How many",fruit,"?",sep=" ")
fruit_number<-readline(string)
print("fruit number")
print(fruit_number)
print("number")
print(number)
while(fruit_number > number){
print("inside while")
print("fruit number")
print(fruit_number)
print("number")
print(number)
print("ERROR: too many for the budget")
string<-paste("How many",fruit,"?",sep=" ")
fruit_number<-readline(string)
}
return(as.numeric(fruit_number))
}
这是我调用此函数的时候:
> source("fruit.R")
> how.many("apple",6)
How many apple ?3
[1] "fruit number"
[1] "3"
[1] "number"
[1] 6
[1] 3
> how.many("apple",10)
How many apple ?9
[1] "fruit number"
[1] "9"
[1] "number"
[1] 10
[1] "inside while"
[1] "fruit number"
[1] "9"
[1] "number"
[1] 10
[1] "ERROR: too many for the budget"
How many apple ?7
[1] "inside while"
[1] "fruit number"
[1] "7"
[1] "number"
[1] 10
[1] "ERROR: too many for the budget"
How many apple ?2
[1] "inside while"
[1] "fruit number"
[1] "2"
[1] "number"
[1] 10
[1] "ERROR: too many for the budget"
How many apple ?1
[1] 1
任何提示?
答案 0 :(得分:1)
将fruit_number
转换为数字,而不是字符串。
e.g。
fruit_number <- as.numeric(readline(string))
或
fruit_number <- as.integer(readline(string))
否则将数字作为字符串进行比较,并且&#34; 9&#34;大于&#34; 10&#34;在字符串意义上。