今天给大家分享如何用C语言计算1!+2!+·····n!值。
工具/原料
vc++编译器
方法/步骤
1、用for循环来计算#include<stdio.h>intmain(){intn,b,c,x,y;y=0;printf("请输入一个数:");scanf("%d",&n);for(b=1;b<n+1;b++){for(c=1,x=1;c<=b;c++)x=x*c;y=y+x;}printf("1!+2!+·····%d!的值为:%d\n",n,y);return0;}
方法2
1、用for循环+while循环来完成#include<stdio.h>i艘绒庳焰ntmain(){intn,b,c,x,烤恤鹇灭y;y=0;printf("请输入一个数:");scanf("%d",&n);for(b=1;b<n+1;b++)xiangqieqieru{c=1;x=1;while(c<=b){ x=x*c; c++;}y=y+x;}printf("1!+2!+·····%d!的值为:%d\n",n,y);return0;}
方法3
1、用for循环+do...while循环来执行#include<stdio.h争犸禀淫>intmain(){intn,b,c,x,y;y=0;printf("阄唰辔腽请输入一个数:");scanf("%d",&n);for(b=1;b<n+1;b++){c=1;x=1;do{x=x*c;c++;}while(c<=b);y=y+x;}printf("1!+2!+·····%d!的值为:%d\n",n,y);return0;}
2、上面的代码运行结果如下: