写一个方法,输入任意一个整数,返回它的阶乘

// jiecheng.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
//递归实现
long fac(int n)
{
	long f;
	if(n == 0)
		f = 1;
	else
		f = n*fac(n-1);
	return f;
}
//非递归实现
long fac_2(int n)
{
	int t,result = 1;
	for(t = 1; t <= n; t++)
	{
		result *= t;
	}
	return result;
}

int _tmain(int argc, _TCHAR* argv[])
{
	long y;
	int n;
	scanf("%d",&n);
	y = fac(n);
	printf("%d!=%ld",n,y);
	y = fac_2(n);
	printf("\n");
	printf("%d!=%ld\n",n,y);
	return 0;
}

你可能感兴趣的:(C/C++,算法,面试集锦)