8.21
递归
递归的本质 一种自己调用自己的函数
具体用法
例如
int f(int n){
if(n==1){
return 1;
}
else{
return n+f(n-1);
}
}
定义
//返回值类型 函数名(变量){
//具体内容
return //跟返回值类型一样
}
错题纠正
B2144
正确思路:使用递归+判断
错误思路:无
正确代码
#include<bits/stdc++.h>
using namespace std;
int f(int m,int n){
if(m==0){
return n+1;
}
if(n==0){
return f(m-1,1);
}
else{
return f(m-1,f(m,n-1));
}
}
int main(){
int n,m;
cin>>n>>m;
cout<<f(n,m);
return 0;
}
B2147
正确思路:使用递归+sqrt函数
错误思路:无
正确代码
#include<bits/stdc++.h>
using namespace std;
double f(int n,double x){
if(n==1){
return sqrt(x+1);
}
else{
return sqrt(n+f(n-1,x));
}
}
int main(){
int n;
double x;
cin>>x>>n;
printf("%.2lf",f(n,x));
return 0;
}
B2148
正确思路:使用递归
错误思路:无
正确代码
#include<bits/stdc++.h>
using namespace std;
double f(int n,double x){//注意类型
if(n==1) return x/(1+x);
return x/(n+f(n-1,x));
}
int main(){
int n;
double x;
cin>>x>>n;
printf("%.2f",f(n,x));
return 0;
}
B2146
正确思路:使用递归
错误思路:无
正确代码
#include<bits/stdc++.h>
using namespace std;
int n,x;
double H(int i){
if(i==0)return 1;
else if(i==1)return 2*x;
else if(i>1) return 2*x*H(i-1)-2*(i-1)*H(i-2);
}
int main(){
cin>>n>>x;
cout<<H(n);
return 0;
}