1、请使用递归实现n!
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int n)
{if(n==1)return 1;else{return n*fun(n-1);}
}int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int s=fun(n);printf("s=%d\n",s);return 0;
}
运行结果:
2、请使用递归实现0-n的和
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int n)
{if(n==0)return 0;else{return n+fun(n-1);}
}int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int s=fun(n);printf("s=%d\n",s);return 0;
}
运行结果:
3、请使用递归实现斐波那契
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int n)
{int s=0;if(n==1)return 1;else if(n==2)return 1;else{return fun(n-1)+fun(n-2);}
}int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);printf("斐波那契数列:");for(int i=1;i<=n;i++){printf("%d ",fun(i));}puts("");return 0;
}
运行结果:
4、请使用递归实现二进制转换
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>void fun(int n)
{if(n==0)return ;else{fun(n/2);printf("%d",n%2);}
}int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);printf("转化为二进制数为:");fun(n);puts("");return 0;
}
运行结果:
5、 请递归实现计算各个位数字之和
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int n)
{if(n/10==0)return n;else{return n%10+fun(n/10);}
}int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int s=fun(n);printf("s=%d\n",s);return 0;
}
运行结果:
6、请递归实现计算各个位数字的乘积
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int n)
{if(n/10==0)return n;else{return (n%10)*fun(n/10);}
}int main(int argc, const char *argv[])
{int n;printf("please enter n:");scanf("%d",&n);int s=fun(n);printf("s=%d\n",s);return 0;
}
运行结果:
7、请使用递归实现计算单词逆置
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void fun(char *p,int low,int high)
{if(low>=high){return ;}else{char t=*(p+low);*(p+low)=*(p+high);*(p+high)=t;fun(p,low+1,high-1);}
}
int main(int argc, const char *argv[])
{char str[20]="";printf("please enter str:");gets(str);int len=strlen(str);fun(str,0,len-1);puts(str);return 0;
}
运行结果: