递归计算n的阶乘

递归计算n的阶乘

fac(n)

n<=1 1
n>1 n*fac(n-1)


#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>

int fac(int x)
{
	if (x <= 1)
		return 1;
	else
	return x*fac(x - 1);
}

int main()
{

	int n = 0;
	printf("请输入您想计算数字的阶乘\n");
    scanf("%d", &n);

	
    int ret = fac(n);
	printf("%d的阶乘为%d",n, ret);

	system("pause");
	return 0;
}

在这里插入图片描述

强调
在递归的时候一定要考虑栈溢出的情况
栈的空间是有限的,如果递归层次太深,数据
会溢出的。即为栈的溢出。
例如此代码不能计算50的阶乘

发布了22 篇原创文章 · 获赞 5 · 访问量 3191

猜你喜欢

转载自blog.csdn.net/weixin_45271990/article/details/104349549