用TC20编一个求n
用TC2.0编一个求n!的值的程序!n尽可能的大!在算完后,由用户自己决定继续求值或退出!用TC2.0编一个求n!的值的程序!n尽可能的大!在算完后,由用户自己决定继续求值或退出!
/*12。26 12:38 修改*/ /*若在TC下不能正确执行,请安装VC,下面是完整的代码,在VC下完全符合你的要求*/ #include void *malloc(int); void free(void *); struct node{ unsigned long data; struct node *Next,*Pro; }; struct link{ struct node *First,*Current,*Last; }; void Insert(struct link *x,struct node *y){ y->Pro=x->Current,y->Next=x->Current->Next; if(x->Last==x->Current) x->Last=y; x->Current=x->Current->Next=y; } void Translate(struct link *x,unsigned long y){ /*把y转成链表形式附加到x后面,重要*/ do{ struct node *NewNode; NewNode=(struct node *)malloc(sizeof(struct node)); NewNode->data=y%10; Insert(x,NewNode); }while((y/=10)>=1); } main(){ struct node FirstNode,*Forfree; struct link LongInt; unsigned long n,ncount; char c; do{ /*带表头结点的双向链表*/ LongInt。
First=LongInt。Last=LongInt。Current=FirstNode。Pro=FirstNode。Next=&FirstNode; printf("Please Input n : "); scanf("\n%d",&n); ncount=n; Translate(&LongInt,n); /*先把n转成链表*/ while (--ncount){ /*这种语法也不知道TC20能不能正确编译。
。。*/ unsigned long Ncarry=0; LongInt。Current=LongInt。First; do{ LongInt。Current=LongInt。Current->Next; LongInt。
Current->data*=ncount; /*先乘以ncount*/ LongInt。Current->data+=Ncarry; /*再加上前一位的进位*/ Ncarry=LongInt。Current->data/10; /*算出往后一位该进位的数*/ LongInt。
Current->data%=10; /*把结果的个位数存储在当前位置*/ }while(LongInt。Current!=LongInt。Last); if(Ncarry) Translate(&LongInt,Ncarry); /*把最高位数的进位数转成链表附加到后面*/ } for(;LongInt。
Current!=LongInt。First;ncount++){ Forfree=LongInt。Current; printf("%d",Forfree->data); LongInt。Current=LongInt。
Current->Pro; free(Forfree); } /*倒序输出,一边输出一边析构*/ printf("\n"); printf(" %d digit of all,Would you like to calculate another one?(Y/N) : ",ncount); scanf("\n%c",&c); }while(c=='y'||c=='Y'); } 。
用递归调用 ` 1 n=0 表示如右 n!={ ` ```````` n*(n-1)! n>0 函数主体如下(预处理我就不写了) flaot asd(int n) { float f; if (n<0) cout<<"n<0,data error!"; else if(n==0||n==1) f=1; else f=asd(n-1)*n; return(f); }
请参考清华大学出版社的>,我记的该书上有一个例子,是用数组存放非常大的整型数求n!,书不在身边,我也不太会。如果是新手就暂时不要搞那么难的,以上各位讲的都是最基本的递归法计算n!,只是n不能很大,否则会溢出。
n尽可能大,就算用float由怎么可以保证不溢出呢,我就的还需要先判断吧,需要给n定出一个范围。
就给5分```晕了```那就提示一下 可心用2种办法` 用递归调用 ` 1 n=0 表示如右 n!={ ` ```````` n*(n-1)! n>0 函数主体如下(预处理我就不写了) flaot asd(int n) { float f; if (n<0) cout<<"n<0,data error!"; else if(n==0||n==1) f=1; else f=asd(n-1)*n; return(f); } 哦`你要决定自已退不退出啊``那你自已去修改吧`` 还一个就是用迭代法!
答:是dos环境 你可以在不同环境下试试吗.详情>>