函数直接调用其自身,称为直接递归,函数间接调用其自身,称为间接递归
列题1:求x的n次方
#include<bits/stdc++.h>
using namespace std;
int x,n;
int xn(int n)
{
if(n==0)
return 1;
else
{
cout<<"chenchen"<<endl;
return x*xn(n-1);
cout<<"yuhog"<<endl;
}
}
int main()
{
cin>>x>>n;
cout<<"xn="<<xn(n)<<endl;
}
分析:chenchen执行了三次,第四的时候是去的是n==0,然后逐层返回,最后返回到主程序,还有个实验是当把
if(n==0) return x=1 写成这样时,最后的结果是1,这说明了虽然前面x是等于2的,但是程序还是只把它当成x当在出口把
x=1,时往后返回时才把x的值给程序,可以尝试把x=3,结果是81
#include<bits/stdc++.h>
using namespace std;
int x;
int t;
int xn(int n)
{
if(n==0)
t=1;
else
{
cout<<"chenchen"<<endl;
xn(n-1);
cout<<"yuhongfu"<<endl;
t*=x;
}
}
int main()
{
int n;
cin>>x>>n;
xn(n);
cout<<"t="<<t<<endl;
return 0;
}
这里先调用xn,等递归结束后才执行下面的语句,其实就是会调用很多层的表达式,然后结束后会返回每个递归的层来执行下面的语句,能执行的原因,没有了return 就不会结束所以会执行下面的语句
例题2:求x!
采用参数函数编写程序
#include<bits/stdc++.h>
using namespace std;
int f(int x)
{
if(x==0)
return 1;
else
return x*f(x-1);
}
int main()
{
int x;
cin>>x;
cout<<f(x)<<endl;;
return 0;
}
采用全局变量
#include<bits/stdc++.h>
using namespace std;
int x;
int sum;
int f(int x)
{
if(x==0)
sum=1;
else
{
f(x-1);
sum*=x;
}
}
int main()
{
cin>>x;
f(x);
cout<<sum<<endl;
return 0;
}
例题3:求最大公约数
#include<bits/stdc++.h>
using namespace std;
int gcd(int m,int n)
{
if(n==0)
return m;
else
return gcd(n,m%n);
}
int main()
{
int m,n;
cin>>m>>n;
cout<<gcd(m,n)<<endl;`9
}
例题4:求数组中的数相加是否能等于m
#include<bits/stdc++.h>
using namespace std;
int a[100];
bool flag;
void sum(int n,int m)
{
if(a[n]==m)
{
flag=true;
return ;
}
else if(n==1) return ;
else
{
sum(n-1,m-a[n]);
sum(n-1,m);
}
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
flag=false;
int m;
cin>>m;
sum(n-1,m);
if(flag) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}
其实就是选与不选的问题
例题5:利用二分查找 在从大到小找x是否在a数组中
#include<iostream>
#include<cstdio>
using namespace std;
int a[11];
void searchh(int x,int L,int R)
{
int mid;
if(L<=R)
{
mid=(L+R)/2;
if(x==a[mid])
cout<<"YES"<<endl;
else
if(x<a[mid]) searchh(x,L,mid-1);
else searchh(x,mid+1,R);
}
else
cout<<"No"<<endl;
}
int main()
{
for(int i=1;i<=10;i++)
{
cin>>a[i];
}
int x;
cin>>x;
int L=1;
int R=10;
searchh(x,L,R);
return 0;
}
再次理解递归