递归函数

*
您的姓名:
*
1.
看程序写结果:
using namespace std;
int n;
int f(int x){
if(x>n)return 0 ;
cout<<x;
f(x+2);
}
int main(){
cin>>n;
f(1);
return 0;
}
输入:10
输出:
*
2.
看程序写结果:
#include<bits/stdc++.h>
using namespace std;
int n;
int f(int x,int y){
if(x==n)return y;
x++;
y=y+x;
f(x,y);
}
int main(){
cin>>n;
cout<<f(1,1);
return 0;
}
输入:5
输出:
*
3.
#include<bits/stdc++.h>
using namespace std;
int f(int x){
if(x<=2)return 1 ;
return f(x-1)+f(x-2);
}
int main(){
int n;
cin>>n;
cout<<f(n);
return 0;
}
输入:7
输出:
4.
作业:数列: 1 2 2 3 3 3 4 4 4 4.....求第n项的值,例如:第4项为3. *
实现程序:
#include<iostream>
using namespace std;
int n;
int f(int k,int x,int y,int z){//k表示当前来到数列第k项,x表示当前项处于第x周期,y是当前项处于当前周期中的第y项,z表示当前项的值
if(k==  [1]  )return z;
if(y== [2]  )f(k+1,x+1,1, [3] );//如果当前周期内项数已填满,则要到下一周期的第一项
else
f(k+1,x,  [4] ,z);//如果当前周期未满,则来到当前周期中的下一项
}
int main(){
cin>>n;
cout<<f(1,1,1,  [5]  );
return 0;
}
问题1:问题2:问题3:问题4:问题5:
5.
把自然数m分解为若干个不同自然数的和,输出每一种分法,从小到大排列.*
输入:10
输出:
10=1+2+3+4
10=1+2+7
10=1+3+6
10=1+4+5
10=1+9
10=2+3+5
10=2+8
10=3+7
10=4+6
10=10
实现程序:
#include<iostream>
using namespace std;
int a[1000]={0};
int m;
int f(int k,int n){
if(n==0){
cout<<m<<"="<<a[1];
for(int i=2;i<=k-1;i++)cout<<"+"<<a[i];
cout<<endl;
return 0;
}
if(n<=a[k-1])return 0;
for(int i=a[ 【1】 ]+1;i<=n;i++){
a[k]=【2】;
f(k+1,【3】);
}
}
int main(){
cin>>m;
a[0]=0;
f(1,【4】);
return 0;
}
问题1:问题2:问题3:问题4:
问卷星提供技术支持
举报