个性化阅读
专注于IT技术分析

c中的析因程序

点击下载

本文概述

C中的阶乘程序:n的阶乘是所有正降序整数的乘积。 n的阶乘由n!表示。例如:

5! = 5*4*3*2*1 = 120
3! = 3*2*1 = 6

来5发音为“ 5阶乘”,也称为“ 5砰”或“ 5尖叫”。

阶乘通常用于组合和排列(数学)。

有很多方法可以用c语言编写阶乘程序。让我们看看两种编写阶乘程序的方法。

  • 使用循环的阶乘程序
  • 使用递归的阶乘程序

使用循环的阶乘程序

让我们看一下使用循环的阶乘程序。

#include<stdio.h>
int main()  
{  
 int i, fact=1, number;  
 printf("Enter a number: ");  
  scanf("%d", &number);  
    for(i=1;i<=number;i++){  
      fact=fact*i;  
  }  
  printf("Factorial of %d is: %d", number, fact);  
return 0;
}

输出:

Enter a number: 5
Factorial of 5 is: 120

在C中使用递归的阶乘程序

让我们看看使用递归的c中的阶乘程序。

#include<stdio.h>

long factorial(int n)
{
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
}
 
void main()
{
  int number;
  long fact;
  printf("Enter a number: ");
  scanf("%d", &number); 
 
  fact = factorial(number);
  printf("Factorial of %d is %ld\n", number, fact);
  return 0;
}

输出:

Enter a number: 6
Factorial of 5 is: 720

赞(0)
未经允许不得转载:srcmini » c中的析因程序

评论 抢沙发

评论前必须登录!