在The R Book中看到的三段循环,不能出结果,很纳闷。求指点!
# loop: factorial
# 1) for
fac1 <- function(x) {
f <- 1
if (x<2)
return (1)
for (i in 2:x) {
f <- f*i
f
}
}
sapply(0:5,fac1)
# 2) while
fac2 <- function(x) {
f <- 1
t <- x # when use while, need to set up an indicator variable: t
while(t>1) {
f <- f*t
t <- t-1 # and change its value within each iteration (t <- t-1)
return(f)
}
}
sapply(0:5,fac2)
# 3) repeat
fac3<-function(x) {
f <- 1
t <- x
repeat { # repeat contains no explicit limit
if (t<2)
break # must have a logical escape clause: break
f <- f*t
t<-t-1
}
return(f)
}
sapply(0:5,fac3)