0
点赞
收藏
分享

微信扫一扫

C语言递归函数使用案例


递归函数

  • 函数自身调用自身,必须有结束条件退出循环

案例

  • 实现字符串逆序遍历
  • 实现斐波那契数列

代码示例:

#define
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//递归函数 函数自身调用自身, 必须有结束条件 跳出循环
//1.实现字符串逆序遍历
void reversePrint(char*p)
{
if (*p == '\0')
{
return; //退出条件
}
reversePrint(p + 1);
printf("%c ",*p);
}
void test01()
{
char*str = "abcdef";
reversePrint(str);
}
//2.斐波那契数列 1 1 2 3 5 8 13
int fibonacci(int pos)
{
if (pos == 1 || pos == 2)
{
return 1;
}
return fibonacci(pos - 1) + fibonacci(pos - 2);
}
void test02()
{
int ret = fibonacci(7);
printf("%d\n",ret);
}
int main()
{
test01();
//test02();
return EXIT_SUCCESS;
}


举报

相关推荐

0 条评论