R 如何解决阶乘函数中十进制数的问题?

R 如何解决阶乘函数中十进制数的问题?,r,decimal,factorial,R,Decimal,Factorial,我正在为阶乘函数编写代码。我的代码如下: f <- function(n) { factorial <- 1 if( n < 0 ) print("Factorial of negative numbers is not possible") else if( n == 0 ) print("Factorial of 0 is 1") else { for(i in 1:n) factorial <- factorial

我正在为阶乘函数编写代码。我的代码如下:

f <- function(n) {
  factorial <- 1
  if( n < 0 )
    print("Factorial of negative numbers is not possible")
  else if( n == 0 )
    print("Factorial of 0 is 1")
  else {
    for(i in 1:n)
      factorial <- factorial * i
    print(paste("Factorial of ",n," is ",factorial))
  }
}

如何在代码中解决此问题?

类似的问题?如果
n
as.integer(n)
不相同,则停止此操作

f <- function(n) {
  if (as.integer(n) != n) {
    stop("The factorial for this number does not exist")
  }
  factorial <- 1
  if( n < 0 )
    print("Factorial of negative numbers is not possible")
  else if( n == 0 )
    print("Factorial of 0 is 1")
  else {
    for(i in 1:n)
      factorial <- factorial * i
    print(paste("Factorial of ",n," is ",factorial))
  }
}


f(5)
# [1] "Factorial of  5  is  120"
f(6.5)
# Error in f(6.5) : The factorial for this number does not exist
f(5/2)
# Error in f(5/2) : The factorial for this number does not exist
f(sqrt(2))
# Error in f(sqrt(2)) : The factorial for this number does not exist

像这样的事?如果
n
as.integer(n)
不相同,则停止此操作

f <- function(n) {
  if (as.integer(n) != n) {
    stop("The factorial for this number does not exist")
  }
  factorial <- 1
  if( n < 0 )
    print("Factorial of negative numbers is not possible")
  else if( n == 0 )
    print("Factorial of 0 is 1")
  else {
    for(i in 1:n)
      factorial <- factorial * i
    print(paste("Factorial of ",n," is ",factorial))
  }
}


f(5)
# [1] "Factorial of  5  is  120"
f(6.5)
# Error in f(6.5) : The factorial for this number does not exist
f(5/2)
# Error in f(5/2) : The factorial for this number does not exist
f(sqrt(2))
# Error in f(sqrt(2)) : The factorial for this number does not exist
请你的代码,这次我帮了你。请你的代码,这次我帮了你。