我多次尝试解决这个问题,但我对循环操作感到困惑..
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j, fact =1, sum =0;
printf("Enter the limit of the factorial series");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
fact = fact * j;
}
sum = sum + fact;
fact = 1;
}
printf("The sum of the factorial series of % d terms is: %d",n,sum);
getch();
}
请给我一个解决问题的提示。
最佳答案
你的内部循环总是计算阶乘(n)
。
创建子函数可能会有所帮助:
int fact(int n)
{
int res = 1;
for (int i = 1; i <= n; ++i) {
res *= i;
}
return res;
}
所以你的主循环变成:
int main()
{
int n,sum = 0;
printf("Enter the limit of the factorial series\n");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
sum = sum + fact(i); // And now it is evident that it is fact(i) and not fact(n).
}
printf("The sum of the factorial series of % d terms is: %d\n", n, sum);
}
或者如果您想在一个循环中完成所有操作
int main()
{
int n;
printf("Enter the limit of the factorial series\n");
scanf("%d", &n);
int sum = 0;
int fact = 1;
for(int i = 1; i <= n; i++) {
fact *= i; // update fact, as Fact(n+1) = Fact(n) * (n+1)
sum += fact;
}
printf("The sum of the factorial series of % d terms is: %d\n", n, sum);
}
关于c - 如何求 1,2,..... 直到 n(输入编号)的阶乘总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31203486/