當前位置:編程學習大全網 - 編程語言 - C語言程序題: 1、編寫壹個求n!的函數fact(n),要求fact函數分別用遞歸和非遞歸兩種方法實現

C語言程序題: 1、編寫壹個求n!的函數fact(n),要求fact函數分別用遞歸和非遞歸兩種方法實現

1。

#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);

}

  • 上一篇:編程軟件是怎樣開發出來的?
  • 下一篇:c語言編程焦急地等待答案。
  • copyright 2024編程學習大全網