实现n!+(n-1)!+...+1!

时间:2023-02-04 17:58:45

首先,设定变量

int p = 1;
int i = 0;
int sum = 0;
int x = 0;

其次,设计阶乘的函数

int jc(int p, int i)
{
for (; i != 1; i -= 1)
p *= i;
return p;
};

最后,设计主函数

int main()
{
printf("求解n!+(n-1)!+...+1!");
printf("请输入n");
scanf_s("%d", &i);\\输入i
for (; i!= 0; i--)\\循环若干次。将值都加给sum
{
x = jc(p, i);\\求解单个数的阶乘
sum += x;\\求和
}
printf("%d", sum);
}

成品:


int jc(int p, int i)
{
for (; i != 1; i -= 1)
p *= i;
return p;
};
int p = 1;
int i = 0;
int sum = 0;
int x = 0;
int main()
{
/*printf("n");*/
printf("请输入n");
scanf_s("%d", &i);
for (; i!= 0; i--)
{
x = jc(p, i);
sum += x;
}
printf("%d", sum);
}