Two ways of C + + to find factorial

Source: Internet
Author: User

  This article mainly introduces the two methods of C + + to find factorial, there is a need for friends can refer to the

1. Use static local variable static local variables to keep the original value after the function call is not gone, that is, the storage unit it occupies is not freed, and the next time the function call, the variable retains the value at the end of the last function call.   Static local variables to the initial value of the actual compile-time, that is, only once the initial value, when the program runs it has the initial value.   Code:   Codes are 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:    code as follows:/* 1!=1 2!=2 3!=6 4!=24 5!=120/    2. The recursive method is used to evaluate the exit recursion first and then recursively &NB Sp Code:   Codes 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; &NBSP}  return 0; }     Print:   code as follows:/* 1!=1 2!=2 3!=6 4!=24 5!=120 *    
Related Article

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.