cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++阶乘
C++阶乘
作者:--    发布时间:2019-11-20

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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册