R 语言循环阶乘



抱歉,我有一个关于 For 循环的问题。

现在有两种不同的循环编码,我的目标是通过 for 循环函数创建一个阶乘。

----------------------------------
Method 1
s<-function(input){
    stu<-1
    for(i in 1:input){
        stu<-1*((1:input)[i]) 
    }
return(stu)
}
 ----------------------------------------
Method 2
k <- function(input){
    y <- 1
    for(i in 1:input){
    y <-y*((1:input)[i])  
    }
return(y)
}

But 1 result is 
> s(1)  
[1] 1  
> s(4)  
[1] 4  
> s(8)  
[1] 8  

and 2 result is 
> k(1)  
[1] 1  
> k(4)  
[1] 24  
> k(8)  
[1] 40320  
-------------------------------

很明显,2是正确的,1是不正确的。 但是为什么?1 和 2 有什么区别? 为什么我不能用stu<-1*((1:input)[i])代替stu<-stu*((1:input)[i])

这是因为变量stufor循环中没有更新。

s<-function(input){
    stu<-1
    for(i in 1:input){ 
            stu<-1*((1:input)[i])
            message(paste(i,stu,sep="t"))
    }
    return(stu) 
}
 s(5)
1   1 # at the first loop, 1 x 1 is calculated
2   2 # at the 2nd loop, 1 x 2 is calculated
3   3 # at the 3rd loop, 1 x 3 is calculated
4   4 # at the 4th loop, 1 x 4 is calculated
5   5 # at the 5th loop, 1 x 5 is calculated
[1] 5

但是,如果使用stu<-stu*((1:input)[i])而不是stu<-1*((1:input)[i])则结果显示以下内容:

s(5)
1   1    # at the first loop,  1 x 1 is calculated.
2   2    # at the second loop, 1 x 2 is calculated.
3   6    # at the third loop,  2 x 3 is calculated.
4   24   # at the fourth loop, 6 x 4 is calculated.
5   120  # at the fifth loop,  24 x 5 is calculated.