R语言循环在阶乘

时间:2018-04-18 01:38:23

标签: r loops for-loop

抱歉,我对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])

1 个答案:

答案 0 :(得分:1)

这是因为变量stu未在for循环内更新。

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.