Two Methods for C ++ to calculate factorial
This article mainly introduces two methods to calculate factorial in C ++. If you need it, refer
1. Use static local variable static
The static local variable does not disappear after the function call and retains the original value, that is, the storage units it occupies are not released. During the next function call, this variable retains the value at the end of the callback function call.
The static local variable assigns the initial value when it is actually compiled, that is, only the initial value is assigned once, and it already has the initial value when the program is running.
Code:
The Code is 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:
The Code is as follows:
/*
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
*/
2. Recursive Method
First exit the recursive judgment, and then perform recursion
Code:
The Code is 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:
The Code is as follows:
/*
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
*/