分别利用递归与迭代(即非递归)求n的阶乘

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//递归求n的阶乘
int Factor(int n){
	if (n == 1){
		return 1;
	}
	return n * Factor(n - 1);
}
//迭代求n的阶乘(非递归)
int Factor_N(int n){
	int ret = 1;	//用来保存每次相乘的结果
	int i;
	for (i = 1; i <= n; ++i){
		ret *= i;	
	}
	return ret;
}
int main(){
	int n;
	printf("请输入一个整数n: \n");
	scanf("%d",&n);
	printf("递归:%d的阶乘为%d\n",n,Factor(n));
	printf("迭代:%d的阶乘为%d\n",n,Factor_N(n));
	system("pause");
	return 0;
}

程序运行结果如下所示:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44781107/article/details/89068623