1 #include <iostream>
2 using namespace std;
3 int jc(int n)
4 {
5 int a=1;
6 if (n<0) cout<<"ERROR!";
7 else if (n==0||n==1) a=1;
8 for(int i=1;i<=n;i++)
9 a=a*i;
10 return a;
11 }
12
13 int main()
14 {
15 cout<<jc(-100)<<endl;
16 cout<<jc(0)<<endl;
17 cout<< jc(5)<<endl;
18
19 return 0;
20 }
以上是循环
下面是递归
1 #include <iostream>
2 using namespace std;
3 int jc(int n)
4 {
5 int a;
6 if(n<0)
7
8 {cout<<"ERROR!";
9 a=-1;
10 }
11 else if(n==0||n==1)a=1;
12 else a = n*jc(n-1);
13
14 return a;
15 }
16
17 int main()
18 {
19 cout<<jc(-100)<<endl;
20 cout<<jc(0)<<endl;
21 cout<< jc(5)<<endl;
22
23 return 0;
24 }