C语言与python与阶乘

阶乘(factorial) n!的概念是 n! = 1* 2* 3*…*n

一般选择用迭代(iteration)或递归(recursion)的方法实现。

C语言:
迭代方法:

#include 
int main()
{
	int n, i, f=1; /*n为需要求阶乘的数字,i为计数器, f为阶乘*/
	
	printf("please give me a number and the i will give you the factorial back ");
	scanf("%d", &n); 
	
	for(i=1; i<=n; i++) /*主体*/
	{
		f*=i;
	}
	
	printf("%d\n", f);
	return 0;
}

递归方法:

#include 
int f(int); /*声明函数f()*/
int main()
{
	int n;
	
	printf("please give me a number i will give you the factorial back to you: ");
	scanf("%d",&n);
	
	printf("%d\n",f(n)); /*将函数f()当作printf的参数,调用并被打印*/
		return 0;
}


int f(int n)  /*定义函数f()*/
{
	
	if(n<=1)
	{
		return 1;
	}
	if(n>1)
	{
		return n*f(n-1);
	}
}  

python:

迭代方法:

n = int(input('please give me a number then i will give you the factorial back '))
factorial = 1
for i in range(1, n+1):
    factorial *= i
print(factorial)

递归方法:

def factorial(n): #定义函数
    if n<=1:
        return 1
    if n>1:
        return n * factorial(n-1)


n = int(input('please give me number... '))
print(factorial(n))

你可能感兴趣的:(C语言与python与阶乘)