我正在写一个阶乘函数的代码。我的代码如下。
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))
}
}
这段代码的问题在于小数点的输入。例如,对于 f(6.5)
我的代码计算出720,但我们知道6.5!不存在。对于十进制数,如 6.5, 5/2
或 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