来总结下求阶乘的各种方法哈。
写在最前:①各个代码只是提供了求阶乘的思路,以便在实际需要时再来编码,代码并不健壮!②各个程序都在1到10内测试正确。
代码一:
- #include<iostream>
- using namespace std;
-
- int fac(int);
-
- int main()
- {
- int n;
-
- while(cin>>n)
- {
- cout<<n<<"!= "<<fac(n)<<endl;
- }
-
- return 0;
- }
-
- int fac(int x)
- {
- register int i,f=1;
-
- for(i=1;i<=x;i++)
- f*=i;
-
- return f;
- }
分析:该程序在每次输入n时,都会调用fac()来暴力计算以得到结果。
代码二:
- #include<iostream>
- using namespace std;
-
- int a[11];
-
- void init();
-
- int main()
- {
- init();
-
- int n;
-
- while(cin>>n)
- {
- cout<<n<<"!= "<<a[n]<<endl;
- }
-
- return 0;
- }
-
- void init()
- {
- int i;
-
- a[0]=1;
- for(i=1;i<=10;i++)
- a[i]=i*a[i-1];
- }
分析:该程序利用了数组记录已得到的结果,并在计算下一个结果时利用了已得到的结果。
代码三:
- #include<iostream>
- using namespace std;
-
- int fac(int);
-
- int main()
- {
- int i;
-
- for(i=1;i<=10;i++)
- {
- cout<<i<<"!= "<<fac(i)<<endl;
- }
-
- return 0;
- }
-
- int fac(int x)
- {
- static int f=1;
-
- f*=x;
-
- return f;
- }
分析:应该说该代码实用性最差,主要是来学习静态局部变量来了。
代码四:
- #include<iostream>
- using namespace std;
-
- int fac(int);
-
- int main()
- {
- int n;
-
- while(cin>>n)
- {
- cout<<n<<"!= "<<fac(n)<<endl;
- }
-
- return 0;
- }
-
- int fac(int x)
- {
- int f;
-
- if(x==0 || x==1)
- f=1;
- else
- f=fac(x-1)*x;
-
- return f;
- }