1.函数递归调用
它是在调用一个函数过程中又出现直接或间接地调用该函数本身
直接递归调用
float func(int n)
{
int m;
float f;
...
f=func(m);
...
}
间接递归调用
funcl(int n)
{
int m;
...
func2(m);
}
func2(int x)
{
int y;
...
func1(y);
}
2.C语言举例
从键盘输入一非负整数n,并求出n!的值。
#include<stdio.h>
long int fact(int n);
int main(void)
{
int n;
long int result;
while(1)
{
printf("Input a number:");
scanf("%d",&n);
if(n>=0)
break;
}//当输入负数时,重复操作,知道输入的数大于等于0为止。while(1)无限循环,是为读取正整数而设置的
result=fact(n);
printf("Result=%ld",result);
}
long int fact(int n)
{
long int f;
if(n==0)
f=1;//不能无限递归下去。当n=0,f=1,因而结束递归调用的过程
else
f=n*fact(n-1);
/**
假设n=4
fact(4)=4*fact(3)
fact(3)=3*fact(2)
fact(2)=2*fact(1)
fact(1)=1*fact(0)
fact(0)=1
总的来说
fact(4)=4*fact(3)
=4*3*fact(2)
=4*3*2*fact(1)
=4*3*2*1*fact(0)
=4*3*2*1*1
**/
return(f);
}
打印从1到10各个数
#include<stdio.h>
void PrintN(int N);
int main(void)
{
int a=10;
PrintN(a);
}
void PrintN(int N)
{
if(N)
{
PrintN(N-1);//直接递归调用
printf("%d\n",N); //这里的问题原因下面给出暂时解释,现作者目前初学无法解释
}//
return;
}//递归调用 递归有时候对空间占用十分恐怖
//若a改为100000,a就爆掉了
由于数据结构预习中,无法解释,先给出目前网上认为不错的解答结论
3.递归调用的优缺点
- 优点:
- 处理问题易于表达
- 程序简洁
- 缺点:运行效率不高,对空间占用十分恐怖(不节省储存空间)