首页 > 代码库 > 函数递归与迭代
函数递归与迭代
递归的缺陷:当运行较多次数的压栈过程会导致运算量过大。可是每个尾递归都能够写成循环(用一个不土的说法就是迭代)
fabonacii数列用迭代方式实现:
#include<stdio.h> int Fibonacii(int n) { int temp = 0; int a = 1;//记得给头两个数赋初值 int b = 1; if(n <= 2) return 1; while(n > 2) { temp = a + b; a = b; b = temp;//切忌写成 a = temp; b = a;这时的a已经改变!=1再赋给b已经没有意义 n--;//调整ab中存放的值向前移动 } return temp; } int main() { printf("%d\n",Fibonacii(6)); return 0; }
用迭代的方式实现阶乘:
#include<stdio.h> int fac(int n) { int ret = 1; while(n) { ret = ret * n; n--;// ret = 1*n,ret = n*(n-1) ....倒着往回乘 } return ret; } int main() { printf("%d\n",fac(3)); return 0; }
函数递归与迭代
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。