Num.3 递归算法
算法思路
递归算法,就是一种直接或者间接地调用自身的算法。具体实现过程一般通过函数或子过程来完成,在函数或子过程的内部,编写代码直接或间接地调用自己,即可完成递归操作。
经典示例:求阶乘
int fact(int n)
{
if(n<=1) return 1; //结束条件
else
return n*fact(n-1);
}
int main()
{
int i;
printf("Please input a num: ");
scanf_s("%d",&i);
printf("The %d! result is:%d\n ",i,fact(i));
while(getchar()!='q');
return 0;
}
示例:数制转换
#include <stdio.h>
#include <string.h>
void conv(char *s, int n, int b)
{
char bit[]={"0123456789ABCDEF"};
int len;
if(0==n)
{
return;
}
conv(s, n/b, b);
len = strlen(s);
s[len] = bit[n%b];
s[len+1] = '\0';
}
int main()
{
char s[30] = {};
int base, old;
printf("Input decimal num: ");
scanf_s("%d",&old);
printf("Input converted: ");
scanf_s("%d",&base);
conv(s, old, base);
printf("%s\n",s);
while(getchar()!='q');
return 0;
}