首先就是求n的阶乘
#include<stdio.h>
//求n的阶乘
int main()
{
int i = 0;
int n = 0;
int ret = 1;//若初始值不为1,那么所求阶乘ret永远为0
scanf("%d", &n);
for (i = 1; i <= n; i++)//i一定要从1开始,否则也是会使阶乘为0
ret = ret * i;//阶乘的计算
printf("ret=%d\n", ret);
return 0;
}
接下来就计算从1的阶乘加到10的阶乘的和
#include<stdio.h>
int main()
{
int i = 0;
int n = 0;
int sum = 0;//阶乘的和
int ret = 1;
for (n = 1; n <= 10; n++)
{
ret = 1;//必须要在这里加上ret=1,用来初始化ret,不让ret保留上一个数的阶乘
for (i = 1; i <= n; i++)
ret = ret * i;
sum = sum + ret;//每个数的阶乘累加
}
printf("sum=%d\n", sum);
return 0;
}
对于阶乘的累加,还有一个优化版本
#include<stdio.h>
int main()
{
int n = 0;
int sum = 0;
int ret = 1;
for (n = 1; n <= 10; n++)
{
ret = ret * n;
sum = sum + ret;
}
printf("sum=%d\n", sum);
return 0;
}
递归法实现求n的阶乘
int Fac(int n)
{
if (n < 1)
return 1;
else
return n * Fac(n - 1);
}
int main()
{
int n;
scanf("%d", &n);
int ret = Fac(n);
printf("ret=%d\n", ret);
return 0;
}