C++ 阶乘程序基础教程文档

收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

C++中的脚步程序: n的阶乘是所有正降序整数的乘积。 n的阶乘由n!表示。例如:
4! = 4*3*2*1 = 24
6! = 6*5*4*3*2*1 = 720  
在这里4!被称为"4阶乘"。
阶乘通常用于组合和置换( Math )。
有用C++语言编写阶乘程序的方法有很多。让我们看看编写阶乘程序的两种方法。
使用循环的程式程序 使用递归的辅助程序

使用循环的基础程序

让我们看看使用循环的C++中的阶乘程序。
#include <iostream>
using namespace std;
int main()
{
   int i,fact=1,number;  
  cout<<"Enter any Number: ";  
 cin>>number;  
  for(i=1;i<=number;i++){  
      fact=fact*i;  
  }  
  cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
  return 0;
}
输出:
Enter any Number: 5  
 Factorial of 5 is: 120   

使用递归的基础程序

让我们看看使用递归的C++中的阶乘程序。
#include<iostream>  
using namespace std;    
int main()  
{  
int factorial(int);  
int fact,value;  
cout<<"Enter any number: ";  
cin>>value;  
fact=factorial(value);  
cout<<"Factorial of a number is: "<<fact<<endl;  
return 0;  
}  
int factorial(int n)  
{  
if(n<0)  
return(-1); /*Wrong value*/    
if(n==0)  
return(1);  /*Terminating condition*/  
else  
{  
return(n*factorial(n-1));      
}  
}
输出:
Enter any number: 6   
Factorial of a number is: 720