2011-05-10 600 views
0
n<-NULL 
acr<-NULL 
while((is.numeric(n)==F) & (acr<0 ¦acr>1)){ 
    print("enter a positive integer and the average cancellation rate you want") 
    try(n<-scan(what=integer(),nmax=1), silent=TRUE); 
    try(acr<-scan(what=double(),nmax=1), silent=TRUE) 
} 

我希望我的程序的用户输入,我存储在“N”,我保持一个正整数,第二 条目“ACR”是其概率介于0和1之间。 (我不希望它是0或1,尽管它可能是根据概率论)。 所以我希望用户继续进行输入,直到他们能够输入“n”的正整数和“acr”的0到1之间的概率值(与AND,OR运算符一起使用)使用while循环使用逻辑运算符(AND和OR)

但是,我遇到了while语句/循环的问题。我尝试了所有其他的可能性,例如下面的可能性,但它仍然不起作用。

while(is.numeric(n)==F & acr<0 ¦acr>1) 

AGAIN:问题2 没有与what=double()也在scan功能的问题,我想。我知道,例如,0.5是其他编程语言中的双数据类型,但是 我无法在R中找到它(我不知道它在R中称为什么)。 R中的integer()double()之间的区别是什么? (我不熟悉双倍)

我会高度赞赏任何人可以来我的援助。

非常感谢大家。

Isaac Owusu

+0

@Owusu艾萨克:尝试在(is.numeric(N)== F&(ACR <0 ¦acr> 1))。您的原始代码首先会评估is.numeric(n)== F&acr <0而不是(我相信您的意图是)is.numeric(n)== F&(acr <0 ¦acr> 1)。 – Jubbles 2011-05-10 14:25:49

回答

1

下面这个例子应该可以工作。请注意,is.integer()

“在不测试,如果‘X’包含 整数!对于这一点,使用 ‘圆’,在函数 ‘is.wholenumber(X)’示例“ (参见help(is.integer))。

因此,我首先定义一个新函数is.wholenumber()

is.wholenumber <- function(x, tol = .Machine$double.eps^0.5){ 
    abs(x - round(x)) < tol 
} 

n <- NULL 
acr <- NULL 
stay.in.loop <- TRUE 

while(stay.in.loop){ 
    print("Please insert n and acr!") 
    n <- readline("Insert n: ") 
    acr <- readline("Insert acr: ") 
    n <- as.numeric(n)  
    acr <- as.numeric(acr) 
    ## stay.in.loop is true IF any of the expressions is NOT TRUE 
    stay.in.loop <- !(is.wholenumber(n) & ((0 < acr) & (acr < 1))) 
} 
+0

适用于readline。请注意这一事实,尽管当输入为空时(按下Enter键)或输入文本时会出现警告时会出现错误。 – 2011-05-12 14:47:56

+0

@Joris Meys:我同意这是一个非常基本的解决方案,它不会检查用户的输入。 – 2011-05-12 15:13:29

0

NULL在这里可能是一个糟糕的初始化,因为它的比较没有给出一个普通的布尔值。由于条件是n应是积极的,试试这个:

n <- -2 
acr <- -2 
while((n<=0) | (acr<0) | (acr>1)) { 
    print("enter a positive integer and the average cancellation rate you want") 
    try(n<-scan(what=integer(),nmax=1), silent=TRUE); 
    try(acr<-scan(what=double(),nmax=1), silent=TRUE); 
} 
+0

满足两个条件时while循环不停止。 – 2011-05-10 15:49:50

+0

尝试应确保它是一个整数。当输入正确时,我会纠正情况停止。我们需要检查n为负数以继续循环。 – highBandWidth 2011-05-10 15:54:47

+0

对不起,你是对的。我刚刚纠正了我的评论:-) – 2011-05-10 15:57:02