C 如何求1,2,…到n的阶乘和(输入编号)

C 如何求1,2,…到n的阶乘和(输入编号),c,C,我多次试图解决这个问题,但我对循环操作感到困惑 #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++

我多次试图解决这个问题,但我对循环操作感到困惑

#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();
}

请给我一个提示来解决这个问题。

你总是在第二个循环中计算事实。您的第二个循环可能如下所示:

for(j=1;j<=i;j++)
{
    fact = fact * j;
}

你的内部循环总是计算factorialn

创建子功能可能有助于:

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);
}

这与Java有什么关系?不要尝试编写多语言源文件。坚持C或C++或Java.变量溢出可能是..,看起来像XY问题的主题,但无效main是错误的。此外,避免CONIO.H和GGCH,因为这些不是标准的。你想做的是java还是C++?在这里粘贴了C++代码。