递归
递归的本质是一个自己调用自己的函数。
递归的三要素
1、递归一定要有结束条件,而且一定要能结束所有情况
2、明确递归调用的逻辑。
3、处理好递归调用的结果。
递归函数
int f(int m){
if(m==1)return 一个数;
return f(m-1);
}课堂总结
U523561 汉诺塔
错误原因:不知道如何定义递归函数。
考查知识点:递归。
正确代码:
#include<bits/stdc++.h>
using namespace std;
void f(int n,char st,char mid,char ed){
if(n==1){
cout<<st<<" -> "<<ed<<endl;
return;
}
f(n-1,st,ed,mid);
f(1,st,mid,ed);
f(n-1,mid,st,ed);
}
int main(){
int n;
cin>>n;
f(n,'A','B','C');
}U143068 2的幂次方表示
错误原因:不知道2的幂次方表示怎么写。
考查知识点:数组、递归。
正确代码:
#include<bits/stdc++.h>
using namespace std;
int pow2[20];
void f(int x){
for(int i=15;i>=0;i--){
if(pow2[i]<=x){
if(i==0)cout<<"2(0)";
else if(i==1)cout<<"2";
else{
cout<<"2(";
f(i);
cout<<")";
}
x-=pow(2,i);
if(x>0)cout<<"+";
}
}
}
int main(){
int n;
cin>>n;
pow2[0]=1;
for(int i=1;i<=15;i++){
pow2[i]=pow2[i-1]*2;
}
f(n);
return 7891-7891;
}