返回类型 函数名称(参数1,参数2,参数3,...){
执行内容
}
返回类型 函数名称(参数1,参数2,参数3,...){
执行内容
...
return 结果
}
return
用于返回函数的运算结果,并结束函数例子
int Sum(int x,int y){
return x + y;
}
斐波那契数列,又称黄金分割数列,因数学家莱昂纳多·斐波那契以兔子繁殖为例子而引入,故又称“兔子数列”,其数值为:0、1、1、2、3、5、8、13、21、34……
问题:请计算出斐波那契数列的第30项
0、1、1、2、3、5、8、13、21、34
规律:从第三项开始,每一项都等于前两项之和
int fib(int index){
int pre_item = 0;
int lat_item = 1;
int result = 0;
if (index == 1) return 0;
if (index == 2) return 1;
for(int i = 3;i <= index;i ++){
result = pre_item + lat_item;
pre_item = lat_item;
lat_item = result;
}
return result;
}
int fib(int index){
if (index == 1) return 0;
if (index == 2) return 1;
return fib(index - 1) + fib(index - 2);
}
什么是递归算法:
递归算法是一种“自己调自己”,“有去有回”的算法,指一种通过重复将问题分解为同类的子问题而解决问题的方法。计算理论可以证明递归的作用可以完全取代循环,因此在很多函数编程语言(如Scheme)中习惯用递归来实现循环。
递归算法的基本特点:
flowchart TD
A[fib 5] --> B[fib 4]
A --> C[fib 3]
B --> D[fib 3]
B --> E[fib 2]
D --> F[fib 2]
D --> G[fib 1]
C --> H[fib 2]
C --> I[fib 1]
F --> J[fib 1]
F --> K[fib 0]
H --> L[fib 1]
H --> M[fib 0]
例题一:请使用递归的方式来计算n的阶乘 $$ f(1) = 1\newline f(2) = f(1) * 2\newline f(3) = f(2) * 3\newline f(4) = f(3) *4\newline $$
#include <iostream>
using namespace std;
int factorial(int n){
if (n == 1){ //设置递归条件
return 1;
}else
return factorial(n-1)*n; //调用自己
}
int main(){
int result = factorial(4);
cout << result << endl;
return 0;
}
例题二:
利用递归算法,试编一程序,计算数组当中最大值
对于数组int a[] = {45, 24, 100, 24, 77, 22, 67, 89}
#include <iostream>
using namespace std;
int _max(int arr[], int len) {
if (len == 1) { // 设置终止条件
return arr[0];
}
int max_item = _max(arr, len - 1); // 求出最大值
if (max_item > arr[len - 1]) { // 求出最大值的条件
return max_item;
} else {
return arr[len - 1];
}
}
int main() {
int a[] = {45, 24, 100, 24, 77, 22, 67, 89};
int max = _max(a, sizeof(a) / sizeof(a[0]));
cout << max << endl;
return 0;
}
练习:
Pell数列$a1,a2,a3,...a1,a2,a3,...$的定义是这样的,$a1=1,a2=2,...,a_n=2a_n−1+a_n−2(n>2)$
给出一个正整数 kk,要求Pell数列的第 kk 项多少。
#include <iostream>
using namespace std;
// 递归函数,计算 Pell 数列的第 n 项
int pell(int n) {
return (n == 1) ? 1 : (n == 2) ? 2 : 2 * pell(n - 1) + pell(n - 2);
}
int main() {
int k;
cout << "请输入正整数 k: ";
cin >> k;
// 计算并输出 Pell 数列的第 k 项
int result = pell(k);
cout << "Pell 数列的第 " << k << " 项是: " << result << endl;
return 0;
}