1

我创建了以下函数来计算给定数字的阶乘:

factorial <- function(x){
y <- 1
for(i in 1:x){
y <-y*((1:x)[i])
print(y)
}

}


factorial(6)

in console:

[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720

6!=720 所以显然最后一个数字是正确的,并且计算确实适用于所有数字。

问题是我只想将最后一个数字打印到控制台,有什么办法吗?我一直在尝试将 y 转换为函数中的向量,但它似乎不起作用。

4

5 回答 5

3

将打印语句移到循环外?

for(i in 1:x){
    y <-y*((1:x)[i])
}
print(y)
于 2013-02-22T00:19:21.437 回答
3

print打印到屏幕上。函数将返回最后一个计算表达式的结果(或显式return值)。你想返回值并打印它吗?

话虽如此

R已经有一个函数factorial调用gamma(x+1),使用整数值的事实gamma(x+1) == x!

所以

factorial(6)

gamma(7)

您编写的函数在乘以大数时会出现整数溢出问题,并且由于您y在循环中反复重新分配(递归时不需要),因此效率非常低

于 2013-02-22T00:23:21.233 回答
0

只需将print()外部循环

factorial <- function(x){
y <- 1
for(i in 1:x){
y <-y*((1:x)[i])
}
print(y)
}

你可以改进这个功能......为什么(1:x)[i]而不只是i?为什么print()而不是return()?最重要的是:为什么不使用factorial()基础包?

于 2013-02-22T00:22:38.023 回答
0
# take input from the user
n <- as.integer(readline(prompt="Enter a number: "))
factorial = 1 #set factorial variable to 1

# check is the number is negative, positive or zero
if(n < 0) {
  print("factorial does not exist for negative numbers")
} else if(n == 0) {
  print("The factorial of 0 is 1")
} else {
  for(i in 1:n) #for loop to expand n up to 1
    {
    factorial = factorial * i 
  }
  print(paste("The factorial of", n ,"is",factorial))
}
于 2017-10-06T10:04:19.393 回答
0

您可以在代码末尾使用 return 函数来定义阶乘函数:

factorial<-function(x){
        y<-1
        for(i in 1:x) {
        y<-y*((1:x)[i])
                      }
        return(y) 
            }
于 2017-11-27T14:06:20.893 回答