1.递归
递归分为,进入和逃离两个部分,分别记录。递到终止条件,归到第一步进入。
递归和迭代:
(1)递归是重复调用函数自身实现循环,满足中止条件逐层返回结束;
(2)迭代是一个重复过程,在上一次的基础上计算/处理。
(3)结构上,递归用选择结构,迭代用循环结构。
(4)递归有栈溢出问题,迭代没有。
2.求n的阶乘(不考虑溢出)
n<=1 1
Fac(n)
n>1 n×Fac(n-1)
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
//求n的阶乘(不考虑溢出)
int Fac1 (int n)
{
int i = 0;
int ret = 1;
for(i=1;i<=n;i++)
{
ret*=i;
}
return ret;
}
int Fac2 (int n)
{
if(n<=1)
{
return 1;
}
else
{
return n*Fac2(n-1);
}
}
int main()
{
int n = 0;
int ret1 = 0;
int ret2 = 0;
printf("请输入阶乘数:\n");
scanf("%d",&n);
ret1 = Fac1(n);
ret2 = Fac2(n);
printf("阶乘结果为:\n");
printf("迭代方式:ret1=%d\n",ret1);
printf("递归方式:ret2=%d\n",ret2);
return 0;
}
3.递归求第n个斐波那契数(不考虑溢出)
斐波那契数列:1 1 2 3 5 8 13 21 后一项等于前两项之和
n<=2 1
Fib(n) 效率低
n>2 Fib(n-1)+Fib(n-2)
TDD:测试驱动开发
先去设计怎么用这个函数,然后再去设计这个函数。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
//递归求第n个斐波那契数(不考虑溢出).
int count = 0;
int Fib (int n)
{
if(n==3)
{
count++;
}
if(n<=2)
{
return 1;
}
else
{
return Fib(n-1)+Fib(n-2);
}
}
int main()
{
int n = 0;
int ret = 0;
printf("求第几个斐波那契数:\n");
scanf("%d",&n);
ret = Fib(n);
printf("第%d个斐波那契数为:%d\n",n,ret);
printf("第3个斐波那契数一共计算了%d次\n",count);
return 0;
}
4.迭代求第n个斐波那契数(优化算法)
1 1 2 3 5 8 13 21
迭代 a b c
a b c
a b c
a b c
效率高
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
//迭代求第n个斐波那契数(优化算法)
int Fib (int n)
{
int a = 1;
int b = 1;
int c = 1;
while(n>2)
{
c=a+b;
a=b;
b=c;
n--;
}
return c;
}
int main()
{
int n = 0;
int ret = 0;
printf("求第几个斐波那契数:\n");
scanf("%d",&n);
ret = Fib(n);
printf("第%d个斐波那契数为:%d\n",n,ret);
return 0;
}
5.满足递归必要条件的栈溢出
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
//满足递归必要条件的栈溢出
void test (int n)
{
if(n<10000)
{
test(n+1);
}
}
int main()
{
test(1);
return 0;
}