1. Use static local variable static
A static local variable retains its original value after the end of the function call, that is, the storage unit it occupies is not freed, and the variable retains the value at the end of the last function call when the function is called.
Static local variable assignment initial value is actually compiled, that is, only once the initial value, when the program is running, it has initial value.
Code
Copy Code code as follows:
#include <iostream>
using namespace Std;
int FAC (int n)
{
static int f=1;
F=f*n;
return F;
}
int main ()
{
int i;
for (i=1;i<=5;i++)
{
cout<<i<< "!=" <<FAC (i) <<endl;
}
return 0;
}
Print
Copy Code code as follows:
/*
1!=1
2!=2
3!=6
4!=24
5!=120
*/
2. Using recursive methods
The first is to exit the recursive judgment and then recursively
Code
Copy Code code as follows:
#include <iostream>
using namespace Std;
int FAC (int n)
{
if (n<0) return 0;
if (n==0| | N==1) return 1;
if (n>1)
{
Return N*FAC (n-1);
}
}
int main ()
{
int i;
for (i=1;i<=5;i++)
{
cout<<i<< "!=" <<FAC (i) <<endl;
}
return 0;
}
Print
Copy Code code as follows:
/*
1!=1
2!=2
3!=6
4!=24
5!=120
*/