我的問題與在 for 回圈中計算 12(階乘)的乘積有關:
我花了很多時間在這個上,但無法解決它!
使用帶有“for”回圈的函式很重要!
到目前為止:我曾嘗試做
for(i in 1:12){
prod(i)
}
并且
for(i in 1:12){
print(prod(i)
}
并且
for(i in 1:12){
prod(i)
}
并且
for(i in 1:12){
print(prod(i)
}
并且
許多其他代碼,它不起作用
uj5u.com熱心網友回復:
對于:
my_factorial<-function(x){
y<-1
for(i in 1:x) {
y<-y*((1:x)[i])
}
return(y)
}
my_factorial(12)
是相同的:
factorial
factorial(12)
或者
您可以gamma用于階乘:
x = 12
gamma(x 1)
是相同的:
12*11*10*9*8*7*6*5*4*3*2*1
[1] 479001600
結果:
[1] 479001600
uj5u.com熱心網友回復:
如果你想在每次迭代中得到第一個數字的乘積
b=vector()
for (i in 1:12){
b[i]=i
print(prod(b))
}
[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720
[1] 5040
[1] 40320
[1] 362880
[1] 3628800
[1] 39916800
[1] 479001600
這會像
1
1*2
1*2*3
.
.
.
1*2*3*4*5*6*7*8*9*10*11*12
但是如果你只想要前 12 個正整數的乘積,那么你就不需要for回圈。只需使用產品功能。
prod(1:12)
[1] 479001600
uj5u.com熱心網友回復:
經過長時間的批判性思考和研究別人的代碼,
我終于能夠創建一個更簡單的代碼,找到高達 12 的階乘
b <- 1:12
這給出了從 1 到 12 的 ba 向量
for(i in 1:1){
print(prod(b))
}
這個函式告訴 r:
對于 i,序列的變數,在 1 行
請列印 b 的產品
回答:
[1] 479001600
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374254.html
