方法一:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main(vodi)
{
//2.计算1!+2!+……n!n个阶乘之和
int i = 0, j=0,n = 0;
int ret = 1,sum=0;
scanf("%d", &n);
for (i = 1; i <=n; i++)
{
ret = 1;//语句A
for (j = 1; j <= i;j++)
ret = j * ret;
sum += ret;
}
printf("%d", sum);
return 0;
}
经典错误:语句A忘记写上,导致ret仍保留上一次运算的结果,产生累加效果!!!
错误情况截图:
正确情况截图:
方法二:
方法一时间复杂度较高为O(N^2),故改进:
运行代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main(vodi)
{
//2.计算1!+2!+……n!n个阶乘之和 方法二:
int i = 0, n = 0;
int ret = 1, sum = 0;
scanf("%d", &n);
for (i = 1; i <=n; i++)
{
ret = ret * i;
sum += ret;
}
printf("%d", sum);
return 0;
}