如何找到1,2,.....的阶乘之和,最多为n(输入编号)

时间:2015-07-03 09:37:47

标签: 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();
}

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

2 个答案:

答案 0 :(得分:2)

您始终在第二个循环中对fact(n)进行计算。你的第二个循环应该是这样的:

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

答案 1 :(得分:2)

您的内部循环始终计算<div class="round-img-button"> <a href="#"> <span class="after">Hover</span> <span class="before">Normal</span> </a> <img src="http://lorempixel.com/100/100" alt="" /> </div>

创建子功能可能会有所帮助:

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