给定数字 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
#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
#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
以上是C程序中的阶乘程序的详细内容。更多信息请关注PHP中文网其他相关文章!