c++编程:递归的编程题

一、累加

#include<bits/stdc++.h>
using namespace std;
int f(int x){
	if(x==1){
		return 1;
	}
	else{
		return x+f(x-1);
	}
}
int main(){
	int n;
	cin>>n;
	cout<<f(n)<<endl;
	return 0;
}

二、阶乘

#include<bits/stdc++.h>
using namespace std;

int f(int x) {
    if(x == 1) {
        return 1;              // 递归终止条件:1! = 1
    }
    else {
        return f(x - 1) * x;   // 递归公式:n! = (n-1)! × n
    }
}

int main() {
    int n;
    cin >> n;
    cout << f(n) << endl;      // 输出 n 的阶乘
    return 0;
}

三、斐波那契数列

斐波那契数 (通常用 f(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:

f(1) = 0
f(2) = 1
f(3) = f(2) + f(1) = 1 + 0 = 1
f(4) = f(3) + f(2) = 1 + 1 = 2
f(5) = f(4) + f(3) = 2 + 1 = 3
f(6) = f(5) + f(4) = 3 + 2 = 5
#include<bits/stdc++.h>
using namespace std;

int f(int x) {
    if(x == 1) {
        return 0;              // 第1项 = 0
    }
    else if(x == 2) {
        return 1;              // 第2项 = 1
    }
    else {
        return f(x-1) + f(x-2); // 递推公式
    }
}

int main() {
    int n;
    cin >> n;
    cout << f(n) << endl;
    return 0;
}

更多推荐