To sum up the methods used to calculate the factorial.
Preface: ① each code only provides the idea of factorial, so that it can be encoded as needed. The code is not robust! ② Each program is tested correctly within 1 to 10.
Code 1:
# 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; // define the register variable for (I = 1; I <= x; I ++) f * = I; return F ;}
Analysis: This program calls FAC () every time it inputs n to obtain the result of brute force computation.
Code 2:
#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];}
Analysis: This program uses the array to record the obtained results, and uses the obtained results when calculating the next result.
Code 3:
# 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; // static local variable F * = X; return F ;}
Analysis: it should be said that the code is the least practical, mainly to learn static local variables.
Code 4:
# 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) // recursive function {int F; if (x = 0 | x = 1) F = 1; elsef = FAC (x-1) * X; return F ;}
Analysis: We always think that recursive technology is amazing. Although not ideal in terms of time and space, it does allow us to use fuzzy programming. You do not have to parse every detail.
Written at the end: the program is a magical thing. Programming is a very important capability.
Welcome!