C语言程序题: 1、编写一个求n!的函数fact(n),要求fact函数分别用递归和非递归两种方法实现

作者&投稿:荤盾 (若有异议请与网页底部的电邮联系)
求阶乘问题。要求定义函数fact(n)计算n!,主函数中输入一个正整数n,输出n!要求函数fact(n)分别采用递归…~

#include "stdio.h"
int fact1(int n)
{
if(n==1||n==0) return 1;
else return n*fact1(n-1);
}
int fact2(int n)
{
int i,t=1;
for(i=1;i<=n;i++)
t*=i;
return t;
}
void main()
{
int n;
scanf("%d",&n);
printf("fact1(n)=%d
",fact1(n));
printf("fact2(n)=%d
",fact2(n));
}

#define RECURSION
#include"stdio.h"
#ifdef RECURSION
long int fact(int n)
{
long int y;
if(n==1)
y=1;
else
y=n*fact(n-1);
return y;
}
#else
long int fact(int n)
{
int i;
long int y=0;
for(i=1;i<=n;i++)
{
y=y*i;
}
return y;
}
#endif
main()
{
int i;
long int y=0;
for(i=1;i<=10;i++)
{
y=y+fact(i);
}
printf("10!=%ld
",y);
getch();
}
注意如果将#define RECURSION 删除,则编译的是非递归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);
}

汗,教科书上都有,自己看去