C++ 求阶乘 四种方法

来源:互联网 发布:178数据库 编辑:程序博客网 时间:2024/06/08 19:40

  来总结下求阶乘的各种方法哈。

           写在最前:①各个代码只是提供了求阶乘的思路,以便在实际需要时再来编码,代码并不健壮!②各个程序都在1到10内测试正确。

 

           代码一:

[cpp] view plain copy
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. int fac(int);  
  5.   
  6. int main()  
  7. {  
  8.     int n;  
  9.   
  10.     while(cin>>n)  
  11.     {  
  12.         cout<<n<<"!= "<<fac(n)<<endl;  
  13.     }  
  14.   
  15.     return 0;  
  16. }  
  17.   
  18. int fac(int x)  
  19. {  
  20.     register int i,f=1;  //定义寄存器变量  
  21.   
  22.     for(i=1;i<=x;i++)  
  23.         f*=i;  
  24.   
  25.     return f;  
  26. }  

            分析:该程序在每次输入n时,都会调用fac()来暴力计算以得到结果。

 

            代码二:

[cpp] view plain copy
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. int a[11];  
  5.   
  6. void init();  
  7.   
  8. int main()  
  9. {  
  10.     init();  
  11.   
  12.     int n;  
  13.   
  14.     while(cin>>n)  
  15.     {  
  16.         cout<<n<<"!= "<<a[n]<<endl;  
  17.     }  
  18.   
  19.     return 0;  
  20. }  
  21.   
  22. void init()  
  23. {  
  24.     int i;  
  25.   
  26.     a[0]=1;  
  27.     for(i=1;i<=10;i++)  
  28.         a[i]=i*a[i-1];  
  29. }  

             分析:该程序利用了数组记录已得到的结果,并在计算下一个结果时利用了已得到的结果。

 

             代码三:

[cpp] view plain copy
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. int fac(int);  
  5.   
  6. int main()  
  7. {  
  8.     int i;  
  9.   
  10.     for(i=1;i<=10;i++)  
  11.     {  
  12.         cout<<i<<"!= "<<fac(i)<<endl;  
  13.     }  
  14.   
  15.     return 0;  
  16. }  
  17.   
  18. int fac(int x)  
  19. {  
  20.     static int f=1;   //静态局部变量  
  21.   
  22.     f*=x;  
  23.   
  24.     return f;  
  25. }  

             分析:应该说该代码实用性最差,主要是来学习静态局部变量来了。

 

            代码四:

[cpp] view plain copy
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. int fac(int);  
  5.   
  6. int main()  
  7. {  
  8.     int n;  
  9.   
  10.     while(cin>>n)  
  11.     {  
  12.         cout<<n<<"!= "<<fac(n)<<endl;  
  13.     }  
  14.   
  15.     return 0;  
  16. }  
  17.   
  18. int fac(int x)   //递归函数  
  19. {  
  20.     int f;  
  21.   
  22.     if(x==0 || x==1)  
  23.         f=1;  
  24.     else  
  25.         f=fac(x-1)*x;  
  26.   
  27.     return f;  
  28. }