作业1 请使用递归实现n!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int m)
{if(m==0)return 1;else{return m*fun(m-1);}
}
int main(int argc, const char *argv[])
{int m;printf("please enter m:");scanf("%d",&m);int sum=fun(m);printf("sum=%d\n",sum);return 0;
}
效果显示:
作业2 请使用递归实现O-n的和
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int m)
{if(m==0)return 0;else{return m+fun(m-1);}
}
int main(int argc, const char *argv[])
{int m;printf("please enter m:");scanf("%d",&m);int sum=fun(m);printf("sum=%d\n",sum);return 0;
}
效果显示:
作业3 请使用递归实现斐波那契
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//斐波那契:任意三项 中间项的平方等于 前一项×后一项 减 1
int fun(int n)
{if(n<=2)return 1;else{return fun(n-1)+fun(n-2);}
}
int main(int argc, const char *argv[])
{int n=0;scanf("%d",&n);printf("第%d个:%d",n,fun(n));puts("");return 0;
}
效果显示:
作业4 请使用递归实现二进制转化
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int fun(int m)
{if(m<2)return m;else{return m%2+fun(m/2)*10;}
}
int main(int argc, const char *argv[])
{int m;printf("please enter m:");scanf("%d",&m);int sum=fun(m);printf("二进制=%d\n",sum);return 0;
}
效果显示:
作业5 请递归实现计算各个位数字之和
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int m)
{if(m==0)return 0;else{return m%10+fun(m/10);}
}
int main(int argc, const char *argv[])
{int m;printf("please enter m:");scanf("%d",&m);int sum=fun(m);printf("sum=%d\n",sum);return 0;
}
效果显示:
作业6 请递归实现计算各个位数字的乘积
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int fun(int m)
{if(m==0)return 1;else{return m%10*fun(m/10);}
}
int main(int argc, const char *argv[])
{int m;printf("please enter m:");scanf("%d",&m);int sum=fun(m);printf("sum=%d\n",sum);return 0;
}
效果显示: