方法1
#include <stdio.h>
int main()
{
int n;
printf("请输入n:");
scanf("%d", &n);
int result = 1;
int sum = 0;
int i = 0;
for(i=1;i<=n;i++)
{
result = result * i; //这一步就是阶乘
sum = sum + result; //这一步就是加法
}
printf("1!+2!+....%d!=%d", n, sum);
}
方法2
for循环内嵌while循环
#include <stdio.h>
int main()
{
int n;
printf("请输入n:");
scanf("%d", &n);
int i = 0;
int j = 0;
int result = 1;
int sum = 0;
//输入及初始化
for (i = 1; i <= n; i++) //计算阶乘
{
result = result * i;
j = 0;
while (j < 1) //做一次加法
//上面的j=0,是为了确保做加法之前j=0,否则一次while循环之后j就等于1,以后不会进入while循环
{
sum = sum + result;
j++; //用于跳出while循环
}
}
printf("1!+2!+....%d!=%d", n, sum);
}
不看内层的j=0和while循环,那么for循环就是一个简单的计算n的阶乘。为了求和,就在得到n的阶乘之后立即做一次加法
方法3
for循环嵌套
#include <stdio.h>
int main()
{
int n;
printf("请输入n:");
scanf("%d", &n);
int i = 0;
int j = 0;
int result = 1;
//输入和初始化
int sum = 0;
for (i = 1; i <= n; i++)
{
result = 1;//内循环要重新算阶乘,但是第二次result不是从1开始,而是保留了算上一个阶乘的值,因此要在循环前重新赋值
for (j = 1; j <= i; j++)
{
result = result * j;
}
sum = sum + result;
}
printf("1!+2!+....%d!=%d", n, sum);
}
外层循环做加法,内层循环计算阶乘。这种效率低
标签:int,scanf,循环,result,计算,printf,阶乘,+..... From: https://blog.csdn.net/Xiejianghao_/article/details/142179859