C + + two ways to find factorial _c language

Source: Internet
Author: User

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
*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.