关于for循环语句后的分号问题#include "Stdio.h"int main(void){long sum=0L;int count=0;int i=0;printf("\nplease enter the number of integers you want to sum:");scanf("%d",&count);for(i=count; i >=1 ;sum += i--) ;printf("\nTotal of the first
来源:学生作业帮助网 编辑:作业帮 时间:2024/07/20 00:32:33
![关于for循环语句后的分号问题#include](/uploads/image/z/5498647-7-7.jpg?t=%E5%85%B3%E4%BA%8Efor%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5%E5%90%8E%E7%9A%84%E5%88%86%E5%8F%B7%E9%97%AE%E9%A2%98%23include+%22Stdio.h%22int+main%28void%29%7Blong+sum%3D0L%3Bint+count%3D0%3Bint+i%3D0%3Bprintf%28%22%5Cnplease+enter+the+number+of+integers+you+want+to+sum%3A%22%29%3Bscanf%28%22%25d%22%2C%26count%29%3Bfor%28i%3Dcount%3B+i+%3E%3D1+%3Bsum+%2B%3D+i--%29+%3Bprintf%28%22%5CnTotal+of+the+first)
关于for循环语句后的分号问题#include "Stdio.h"int main(void){long sum=0L;int count=0;int i=0;printf("\nplease enter the number of integers you want to sum:");scanf("%d",&count);for(i=count; i >=1 ;sum += i--) ;printf("\nTotal of the first
关于for循环语句后的分号问题
#include "Stdio.h"
int main(void)
{
long sum=0L;
int count=0;
int i=0;
printf("\nplease enter the number of integers you want to sum:");
scanf("%d",&count);
for(i=count; i >=1 ;sum += i--) ;
printf("\nTotal of the first %d number is %ld;\ni=%d.\n",count,sum,i);
}
for语句后的分号不加的话,sum的结果就是从2加到count,但是加的话,sum的结果就是从1加到count.
为什么会这样!
关于for循环语句后的分号问题#include "Stdio.h"int main(void){long sum=0L;int count=0;int i=0;printf("\nplease enter the number of integers you want to sum:");scanf("%d",&count);for(i=count; i >=1 ;sum += i--) ;printf("\nTotal of the first
for(表达式1;表达式2;表达式3) 语句
执行过程如下:
1) 先求解表达式1.
2) 求解表达式2,若其值为真,则执行for语句中指定的内嵌语句,然后执行下面第3)步;若其值为假,则结束循环,转到第5)步.
3) 求解表达式3.
4) 转回上面第2)步继续执行.
5) 循环结束,执行for语句下面的一个语句.
有分号时就是没有循环体时,等于是直接跳到3)步,去求表达式3了,也就是表达式3成为循环体,等价于
for(i=count; i >=1 ;i--)
sum=sum+i;
此后printf打出的是它执行完时sum的终值.
而没分号时循环体为printf语句,也就是说第一次并不是求表达式3,而是先去执行printf了,----这就是为什么第一次打出的sum总为0!也就是printf先于sum += i--执行了.
总之,两种情况下,sum += i--语句执行次数是一样的,但在没分号情况下,因printf要比它早执行一次,因而最后sum终值没有被打出来而已.