十、函数和递归(3)

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;
}

6.汉诺塔

7.青蛙跳台阶

8.思维导图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值