[C program] Find factorial using recursive method

Idea analysis:

We demand n! , n!=n*(n-1)!, until the recursion termination condition 1! =1, the summary formula is as follows:

 Implementation process

 Code

#include <stdio.h>
int main()
{	int fac(int n);		//fac函数声明
	int n,y;
	printf("输入一个整数:");
	scanf("%d",&n);	//输入要求阶乘的数
	y=fac(n);
	printf("%d!=%d\n",n,y);
	return 0;
}
int fac(int n) 				//定义fac函数
{
	int f;
	if(n<0)				//n不能小于0
		printf("n<0,数据错误!");
	else if(n==0||n==1)	//n=0或,1时n!=1
		f=1;				//递归终止条件
	else
		f=fac(n-1)*n;	 //n>1时,n!=n*(n-1)
	return(f);
}

Precautions

The variables in the program are of type int . Int type data is allocated 4 bytes. The maximum number that can be represented is 2 147 483 647. When n=12 , the operation is normal and the output is 479 001 600 . If you enter 13 and try to find 13!, you will not get the expected result because the result exceeds the maximum value of int type data. The f, y and fac functions can be defined as float or double types to increase the range of numerical representation.

Guess you like

Origin blog.csdn.net/studyup05/article/details/130925029