递归函数(要求fact函数分别用递归和非递归两种方法实现)

伏羲号

1。

递归函数(要求fact函数分别用递归和非递归两种方法实现)

#include "stdio.h"

//#define RECURSION 1

#ifdef RECURSION

long fact(int n)

{

if(n<1) return 1;

return n*fact(n-1);

}

#else

long fact(int n)

{

long t=1;

for(int i=2;i<=n;i++)

t*=i;

return t;

}

#endif

main()

{

long s=0;

for(int i=1;i<=10;i++)

s+=fact(i);

printf("%ld\n",s);

}

2。

#include "stdio.h"

bool prime(int n)

{

if(n==1) return false;

for(int i=2;i<=n/2;i++)

if(n%i==0) return false;

return true;

}

main()

{

int cnt=0;

int i=3;

while(cnt<10)

{

if(prime(i) && prime(i+2))

{

printf("(%d,%d)\n",i,i+2);

cnt++;

}

i+=2;

}

}

3。

非递归

#include "stdio.h"

void main()

{

int s=0,total=0;

int day=0;

while(s<100)

{

if(day%2==0)

{

s+=3;

total+=3;

}

else

{

s-=2;

total+=2;

}

day++;

}

if(s>100) total-=(s-100);

printf("total %d days,climb %d metres\n",day,total);

}

递归

#include "stdio.h"

struct node{

int day;

int total;

};

struct node f(int dest,int tag)

{

if(tag==0)

{

if(dest<=3)

{

struct node temp;

temp.day=1;

temp.total=dest;

return temp;

}

else

{

struct node temp,temp1;

temp1=f(dest-3,1);

temp.day=temp1.day+1;

temp.total=temp1.total+3;

return temp;

}

}

else

{

struct node temp,temp1;

temp1=f(dest+2,0);

temp.day=temp1.day+1;

temp.total=temp1.total+2;

return temp;

}

}

void main()

{

struct node a=f(100,0);

printf("total %d days,climb %d metres\n",a.day,a.total);

}

发表评论

快捷回复: 表情:
AddoilApplauseBadlaughBombCoffeeFabulousFacepalmFecesFrownHeyhaInsidiousKeepFightingNoProbPigHeadShockedSinistersmileSlapSocialSweatTolaughWatermelonWittyWowYeahYellowdog
评论列表 (暂无评论,71人围观)

还没有评论,来说两句吧...