递归和非递归求n的阶乘
#include <stdio.h>
int sum1(n)//循环法求阶乘
{
int sum = 1;
int i = 1;
for (i = 1; i <= n; i++)
{
sum = sum * i;
}
return sum;
}
int sum2(n)//递归方法求阶乘
{
int sum = 0;
if (n == 1)
{
sum = 1;
}
else
{
sum = sum2(n - 1) * n;
}
return sum;
}
void Menu() {
printf("1 用循环法求阶乘\n");
printf("2 用递归法求阶乘\n");
printf("3 退出\n");
}
int main()
{
int sum = 1;
int n,c;
printf("输入要求的阶乘 n :");
scanf("%d", &n);
Menu();
while (1)
{
printf("\n输入菜单: ");
scanf("%d", &c);
switch (c)
{
case 1:
sum = sum1(n);
printf("sum1 = %d", sum);
break;
case 2:
sum = sum2(n);
printf("sum2 = %d", sum);
break;
case 3:
break;
default:
break;
}
if (c == 3)
break;
}
return 0;
}