C 程式中計算一個數的階乘的程式


給定一個數 n,任務是計算它的階乘。一個數的階乘是透過將它乘以它本身或更小的整數來計算的。

階乘的計算方法如下。

0! = 1
1! = 1
2! = 2X1 = 2
3! = 3X2X1 = 6
4! = 4X3X2X1= 24
5! = 5X4X3X2X1 = 120
.
.
.
N! = n * (n-1) * (n-2) * . . . . . . . . . .*1

示例

Input 1 -: n=5
   Output : 120
Input 2 -: n=6
   Output : 720

實現這一目標有多種方法。

  • 透過迴圈
  • 透過遞迴,但這種方法不太有效
  •  透過一個函式

下面是用函式實現的。

演算法

Start
Step 1 -> Declare function to calculate factorial
   int factorial(int n)
      IF n = 0
         return 1
      End
      return n * factorial(n - 1)
step 2 -> In main()
   Declare variable as int num = 10
   Print factorial(num))
Stop

用 C

示例

#include<stdio.h>
// function to find factorial
int factorial(int n){
   if (n == 0)
   return 1;
   return n * factorial(n - 1);
}
int main(){
   int num = 10;
   printf("Factorial of %d is %d", num, factorial(num));
   return 0;
}

輸出

Factorial of 10 is 3628800

用 C++

示例

#include<iostream>
using namespace std;
// function to find factorial
int factorial(int n){
   if (n == 0)
   return 1;
   return n * factorial(n - 1);
}
   int main(){
   int num = 7;
   cout << "Factorial of " << num << " is " << factorial(num) << endl;
   return 0;
}

輸出

Factorial of 7 is 5040

更新於: 20-9 月-2019

643 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.