C++ 学习笔记_0016_递归(斐波那契数列、进制转换、最大公约数、汉诺塔)

来源:互联网 发布:it监控软件排名 编辑:程序博客网 时间:2024/05/01 22:08
【项目1-Fibnacci序列】
输出Fibnacci序列的第20个数。要求提交两个程序,fib(int n)的实现分别用迭代方法与递归方法实现。

提示:如实现困难,先从讲义看求阶乘的迭代方法与递归方法实现,深入体会后再进行设计。

#include<iostream>using namespace std;int fib(int);int main(){    cout << fib(20) << endl;    return 0;}//迭代法/*int fib(int n){    int f, f1, f2, i;    if (n == 1)        return 0;    else if (n == 2)        return 1;    else    {        f1 = 0;        f2 = 1;        for (i = 3; i <= n; i++)        {            f = f1 + f2;            f1 = f2;            f2 = f;        }    }    return f2;}*///递归法int fib(int n){    if (n == 1)        return 0;    else if (n == 2)        return 1;    else        return (fib(n-1) + fib(n-2));}

进制转换

#include<iostream>using namespace std;void dec2bin(int);int main(){    int n;    cout << "请输入一个大于0的整数:";    cin >> n;    cout << endl << n << "对应的二进制数为:";    dec2bin(n);    cout << endl;    return 0;}void dec2bin(int n){    if (n == 0)        return;    else    {        dec2bin(n/2);        cout << n%2;        return;    }}

最大公约数

#include<iostream>using namespace std;int gcd(int, int);int main(){    int m, n;    cout << "输入两个整数:";    cin >> m >> n;    cout << "最大公约数:";    cout << gcd(m, n) << endl;    return 0;}//迭代法/*int gcd(int a, int b){    int t, r;    if (a < b)        t = a, a = b, b = t;    while (b != 0)    {        r = a % b;        a = b;        b = r;    }    return a;}*///递归法int gcd(int a, int b){    int t, g;    if (b == 0)        g = a;    else        g = gcd(b, a%b);    return g;}

汉诺塔

#include<iostream>using namespace std;const int dissCount = 3;long move(int, char, char, char);int main(){    long count;    count = move(dissCount, 'A', 'B', 'C');    cout << dissCount << "个盘子需要移动" << count << "次。" << endl;    return 0;}long move(int n, char A, char B, char C){    long c1, c2;    if (n == 1)    {        cout << A << " ---> " << C << endl;        return 1;    }    else    {        c1 = move(n-1, A, C, B);        cout << A << " ---> " << C << endl;        c2 = move(n-1, B, A, C);        return c1 + c2 + 1;    }}

0 0