C++中的阶乘程序:n
的阶乘是所有正整数的乘积。 n
的阶乘由n!
表示。 例如:
4! = 4*3*2*1 = 24
6! = 6*5*4*3*2*1 = 720
这里,4!
发音为“4阶乘”。
阶乘通常用于组合和排列(数学)。
有很多方法用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