最近整理了曾经写的程序,把n的阶乘三种实现方法与小伙伴们分享,希望能给初学者一些帮助。
1、递归
#include <stdio.h>
int Fact(int n);
int main()
{
int number,result; //number 为待输入的数,计算number的阶乘
printf("please input number");
scanf("%d",&number);
result=Fact(number);
printf("%d的阶乘是%d",number,result);
return 0;
}
int Fact(int n) //递归函数
{
int res=n;
if(n>1)
res=res*Fact(n-1);
return res;
}
2、栈(递归的本质,实现基于栈这一存储方式)
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
struct SeqStack{ //定义控制单元
int MAXNUM;
int t;
DataType *s;
};
typedef struct SeqStack *PSeqstack; // 此处,实际上是定义一种数据类型(struct SeqStack *),返回指针。可以理解为返回struct SepStack 的地址,
//函数声明
int Fact(int n);
PSeqstack createEmptyStack_seq(int m); //创建空栈
void Push_seq(PSeqstack pstack,DataType x); //入栈函数
DataType isEmptyStack_seq(PSeqstack pstack); //判断栈是否为空的函数
DataType top_seq(PSeqstack pstack); //取栈顶元素的函数
void pop_seq(PSeqstack pstack); //出栈函数
int main()
{
PSeqstack pstack; //用于存放控制单元的地址
int n,MUL;
printf("Please input the value of n:");
scanf("%d",&n);
MUL=Fact(n); //计算n的阶乘,值赋给MUL
printf("%d",MUL);
return 0;
}
int Fact(int n)
{
int res;
PSeqstack st;
st=createEmptyStack_seq(n); //创空栈,返回指针(指向控制单元的地址),赋给st
while(n>0) //如果n大于0,就继续将元素压栈
{
Push_seq(st,n);
n=n-1;
}
res=1;
while(!isEmptyStack_seq(st)) //如果栈不空 ,则取栈顶元素 ,然后将从栈中弹出此元素
{
res=res*top_seq(st);
pop_seq(st);
}
free(st); //释放空间
return res; //返回n的阶乘
}
PSeqstack createEmptyStack_seq(int m) //创建空栈
{
PSeqstack pstack=(PSeqstack)malloc(sizeof(struct SeqStack));
if(pstack!=NULL){
pstack->s=(DataType *)malloc(sizeof(DataType)*m);
if(pstack->s){
pstack->MAXNUM=m;
pstack->t=-1;
return pstack;
}
}
}
void Push_seq(PSeqstack pstack,DataType x)
{
if(pstack->t>=pstack->MAXNUM-1) //压栈时,判断栈元素是否已满
printf("Overflow!\n");
else{
pstack->t=pstack->t+1;
pstack->s[pstack->t]=x;
}
}
int isEmptyStack_seq(PSeqstack pstack) //判空函数,判断栈顶变量是否为-1
{
if(pstack->t==-1)
return 1;
else
return 0;
}
DataType top_seq(PSeqstack pstack)
{
if(pstack->t==-1)
printf("It is empty\n");
else
{
return (pstack->s[pstack->t]); //返回栈顶元素
}
}
void pop_seq(PSeqstack pstack)
{
if(pstack->t==-1)
printf("Underflow\n");
else
pstack->t=pstack->t-1; //出栈函数,元素出栈后,栈顶变量减1
}
3 for循环
#include <stdio.h>
int main()
{
int i,n,Mul;
Mul=1;
printf("请输入n值:");
scanf("%d",&n);
for(i=n;i>0;i--)
{
Mul=Mul*n;
n=n-1;
}
printf("%d",Mul); //打印n的阶乘Mul
}
这些程序都比较简单,初学C语言的话,可能第二个程序比较费劲,学了数据结构自然就不存在问题了。