R语言之斐波那契数列
作者:互联网
#斐波那契数列
#1,1,2,3,5,8,13,21,34,....
a=1;b=1
qing <- function(x){
for (i in 1:5){
print(a)
c = a +b
a =b
b =c
}
}
qing(5)
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
# c = a +b 将a+b 赋值给c
#a =b 把b赋值给a,a原来的值被覆盖掉
#b =c 把c赋值给b,b原来的值被覆盖掉
#a是更新最慢的,从而将每个数都给打印出来
###这里采用了循环,是为了提示运行次数或兔子问题中的繁殖代数
a=1;b=1;i=0
wo <- function(x){
while(i <= x) {
print(a)
c = a +b
a =b
b =c
i = i + 1
}
}
wo(5)
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
##和第一个类似
wo <- function(x){
if (x ==1 || x == 2){
return(1)
}else{
return(qing(x-1) + qing(x-2))
}
}
wo(6)
[1] 8
##采用了递归的编程思想。
标签:13,qing,数列,....,之斐波,那契,21 来源: https://blog.csdn.net/u010608296/article/details/120709784