Two Methods for C ++ to calculate factorial

Source: Internet
Author: User

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

*/

 

 

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.