栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

函数之递归迭代

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

函数之递归迭代

1、递归预防栈溢出、不能陷入死递归无法自拔、递归层次不能太深

2、递归要有跳出条件、每次递归必须逼近跳出条件

问:给一个数1234,分别按顺序输出1 2 3 4
#include
using namespace std;
int strl(int n)
{
	int cout;
	if(n==0)
	return 1;
	while(n%10)
	{
		cout++;
		n/=10;
	}
	return cout;
}
int mi(int x)
{
	int re=1;
	for(int i=1;i 

初版代码:

写了两个函数strl(取位数)mi(取10的幂)在递归函数里调用,脑子抽了,好麻烦啊!!比存数组还麻烦

其实在打印前递归就很好的解决了这个问题

#include
using namespace std;
void digui(int n)
{
	if(n==0)return ;
   digui(n/10);
   printf("%d ",n%10);
}
int main()
{
	digui(1234);
	return 0;
}

这种情况下是1 2 3 4

void digui(int n)
{
	if(n==0)return ;
	printf("%d ",n%10);
   digui(n/10);
   
}

这样就是4 3 2 1

用递归写strlen()

int my_strlen(char *str)
{
	if(*str!='')
	return 1+my_strlen(str+1);
	return 0;
}

斐波那契:
int Fib(int n)
{
	if(n<=2)
	return 1;
	return Fib(n-1)+Fib(n-2);
}

 这样效率低

 可以用迭代

int Fib(int n)
{
	int a=1,b=1,c=1;
	while(n>2)
	{
		c=a+b;
		a=b;
		b=c;
		n--;
	}
	return c;
}
阶乘:
int Fac(int n)
{
	if(n<=1)
	return 1;
	return n*Fac(n-1);
}
汉诺塔:
#include
using namespace std;
void move(char beg,char end)
{
	cout<"<>n;
	hanoi(n,'A','B','C');
	return 0;
	
 } 
青蛙跳台阶:
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/699045.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号