如何使用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) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值