簡體   English   中英

階乘for循環

[英]Factorial for loop

我創建了以下函數來計算給定數字的階乘:

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轉換為函數中的向量,但似乎不起作用。

將打印語句移到循環之外?

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

print打印到屏幕上。 函數將返回上一次求值表達式的結果(或顯式return值)。 您是否要返回值並打印它?

話雖如此

R已經有一個函數factorial ,它調用gamma(x+1) ,事實是對於整數值gamma(x+1) == x!

所以

factorial(6)

gamma(7)

您編寫的函數在乘以大數時將出現整數溢出問題,並且由於在循環中反復將y重復分配給y而效率極低(不需要時遞歸)

只需將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()

# 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))
}

您可以在代碼末尾使用return函數來定義階乘函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM