跳到正文

个人记录

8.21

xazxazxaz约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

递归

递归的本质 一种自己调用自己的函数

具体用法

例如

C++
int f(int n){
	if(n==1){
		return 1;
	}
	else{
		return n+f(n-1);
	}
}

定义

代码
//返回值类型  函数名(变量){
    //具体内容
    return //跟返回值类型一样
}

错题纠正

B2144

正确思路:使用递归+判断

错误思路:无

正确代码

C++
#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函数

错误思路:无

正确代码

C++
#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

正确思路:使用递归

错误思路:无

正确代码

C++
#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

正确思路:使用递归

错误思路:无

正确代码

C++
#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;
}
原文