递归练习题
输入1234,输出1 2 3 4
/*
输入1234,输出1 2 3 4
*/
#include <stdio.h>
void print(int n)
{
if (n > 9)
print(n / 10); // 当n>9时,会进行递归
printf("%d ", n % 10);
}
int main()
{
int num = 0;
scanf("%d", &num);
print(num);
return 0;
}
编写函数不允许创建临时变量,求字符串的长度。
/*
编写函数不允许创建临时变量,求字符串的长度。
*/
#include <stdio.h>
int Strlen(char* str)
{
if (*str != '\0')
// 当传进来的str所对应的字符不是字符串的结束符,+1并且str往后移一位
return 1 + Strlen(str + 1);
else
return 0;
}
int main()
{
char arr[] = "bhlu";
printf("%d\n", Strlen(arr));
return 0;
}
求n的阶乘。(不考虑溢出)
/*
求n的阶乘。(不考虑溢出)
*/
#include <stdio.h>
int fac(int num)
{
if (num > 2)
return num * fac(num-1);
else
return num;
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("%d\n", fac(n));
return 0;
}
求第n个斐波那契数。(不考虑溢出)
/*
求第n个斐波那契数。(不考虑溢出)
*/
/*
递归方法:
当n<=2时, 1;
当n>2时, f(n-1)+f(n-2);
发现递归方法出现太多重复的计算
*/
#include <stdio.h>
int count = 0;
int fib(int n)
{
if (n == 3)
count++; // 计算第三个斐波那契数次数
if (n > 2)
return fib(n - 1) + fib(n - 2);
else
return 1;
}
int main()
{
int num = 0;
scanf("%d", &num);
printf("%d\n", fib(num));
printf("count=%d\n", count);
return 0;
}
/*
循环的方法
1 1 2 3 5 8 13 21
1 a b c c=1
2 a b c c=1
3 a b c a=1;b=1;c=a+b;
4 a b c b->a;c->b;c=a+b;
*/
#include <stdio.h>
// n代表是第几个
int fib(int n)
{
int a = 1;
int b = 1;
int c = 1;
while (n > 2)
{
a = b;
b = c;
c = a + b;
n--;
}
return c;
}
int main()
{
int num = 0;
scanf("%d", &num);
printf("%d\n", fib(num));
}
汉诺塔
诺塔问题是一个经典的问题。汉诺塔(Hanoi Tower),又称河内塔,源于印度一个古老传说。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,任何时候,在小圆盘上都不能放大圆盘,且在三根柱子之间一次只能移动一个圆盘。问应该如何操作?
#include <stdio.h>
int count = 0;
// 打印移动轨迹 pos1是源地址,pos2是目标地址
void move(char pos1, char pos2)
{
count++;
printf("第%d次\t %c->%c\n", count, pos1, pos2);
}
/*
实现的汉诺塔的函数
n: 几块板子
pos1: 源点
pos2: 中转点
pos3: 目标点
*/
void Hanoi(int n, char pos1, char pos2, char pos3)
{
if (1 == n)
{
move(pos1, pos3);
}
else
{
Hanoi(n - 1, pos1, pos3, pos2); // 将pos1上的除最后一块移到pos2上,通过pos3中转
move(pos1, pos3); // 此时pos1上还剩一块最大的,再将pos1上的移到pos3上
Hanoi(n - 1, pos2, pos1, pos3); // 最后再将pos2上的移到pos3上,通过pos1中转
}
}
int main()
{
int n = 0;
scanf("%d", &n);
Hanoi(n, 'A', 'B', 'C');
return 0;
}
青蛙跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个n级的台阶总共有多上种跳法。
#include <stdio.h>
int frog(int n)
{
if (n <= 2)
return n;
else
return frog(n - 1) + frog(n - 2);
}
int main()
{
int num = 0;
printf("请输入有几个台阶:>");
scanf("%d", &num);
printf("共有%d种\n", frog(num));
return 0;
}