其他分享
首页 > 其他分享> > 如何使用C语言来计算n的阶乘?(递归?)

如何使用C语言来计算n的阶乘?(递归?)

作者:互联网

 RT,这个问题看似很复杂,其实看过代码后很容易就能理解

需要注意的是,这个问题可以使用递归也可以不递归,都没问题

下面递归和非递归的代码都有

由于我的编译器是VS2019,scanf需要加上_s,其它编译器把_s去掉即可 

我们先看递归的代码,应该能看懂注释,我就不多解释来(dog)


//求 n!(递归)
#include<stdio.h>
int factorial(int n);//在main函数前声明fac函数
int main(void)
{
	int n;
	printf("Please input the n :\n");
	scanf_s("%d", &n);
	int result = factorial(n);
	printf("The result is %d\n", result);
	return 0;
}

//定义fac函数并通过fac函数以及递归来计算 阶乘
int factorial(int n)
{
	int total;
	if (n == 1)
		return 1;
	else
		total = n * factorial(n - 1);//使用递归
	return total;//返回n的阶乘
}

下面是非递归的代码

//求 n!(非递归)
#include<stdio.h>
int factorial(int n);//在main函数前声明fac函数
int main(void)
{
	int n;
	printf("Please input the n :\n");
	scanf_s("%d", &n);
	int result = factorial(n);
	printf("The result is %d\n", result);
	return 0;
}

//定义fac函数并通过fac函数来计算 n的阶乘
int factorial(int n)
{
	int total=1,i;
	if (n == 0)
		total = 0;
	for (i = 1; i <= n; i++)
		total *= i;
	return total;//返回total的值(阶乘)
}

到这里就没什么可说的了,希望能帮助到你,Byb~ 

(PS:代码都是手打的,并非直接ctrl c+v) 

标签:递归,int,C语言,factorial,result,阶乘,fac,total
来源: https://blog.csdn.net/qq_61025926/article/details/121617555