c - 如何求 1,2,..... 直到 n(输入编号)的阶乘总和

标签 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++)
       {
          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/

相关文章:

c - 为什么我的代码多次打印整个字符串而不是 1 次?

Python 到 C/C++ const char 问题

c - 无法使 libtool 合并 yasm 创建的目标文件

c - 程序的输出与预期不同

c - 使用 RSA_public_encrypt 加密/解密没有填充的单个八位字节

c - 给定一个指针,找到它所在的堆 block

c - struct 数组按值传递,而不是按引用传递

c - VS2005 禁用内联

C代码小波变换及解释

c - 用 C 编写内核的资源