C 中的阶乘程序
2021-07-06 21:48:02
深夜i
--
--
C
的
阶
乘
程
序
在 C 中使用 for 循环、使用递归和创建函数的阶乘程序。 阶乘用'!'表示,所以五个阶乘写成(5!),n阶乘写成(n!)。 还有,n! = n*(n-1)*(n-2)*(n-3)...3.2.1 零阶乘定义为 1,即 0! = 1。
C 中使用 for 循环的因子
#include <stdio.h>
int main()
{
int c, n, f = 1;
printf("Enter a number to calculate its factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
f = f * c;
printf("Factorial of %d = %d\n", n, f);
return 0;
}
作为 n! 以比指数函数 2n 更快的速度增长,如果我们使用内置数据类型,即使是两位数也会发生溢出。 要计算这些数字的阶乘,我们需要使用数组或字符串等数据结构。
C 中使用递归的阶乘程序
#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;
printf("Enter an integer to find its factorial\n");
scanf("%d", &n);
if (n < 0)
printf("Factorial of negative integers isn't defined.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}
return 0;
}
long factorial(int n)
{
if (n == 0) // Base case
return 1;
else
return (n*factorial(n-1));
}
在递归中,函数调用自身。 在上面的程序中,阶乘函数正在调用自身。 要使用递归解决问题,您必须首先以递归形式表达其解决方案。
求一个数的阶乘的C程序
#include <stdio.h>
long factorial(int);
int main()
{
int n;
printf("Enter a number to calculate its factorial\n");
scanf("%d", &n);
printf("%d! = %ld\n", n, factorial(n));
return 0;
}
long factorial(int n)
{
int c;
long r = 1;
for (c = 1; c <= n; c++)
r = r * c;
return r;
}
为了计算排列、组合的数量以及计算概率,我们使用阶乘。
上一篇:
idea打包java可执行jar包
下一篇:
查找 HCF 和 LCM 的 C 程序
评论区