问题描述
我想知道为什么这两个代码给出了不同的结果; 这个数字给出了1个包含的数字和10个被排除的数字。对于(i = 1,j = 0; i j + = i, 然而这个给出了10.我无法得到这个逻辑; 这是因为迭代的默认范围是只有跟在它后面的行,在你的情况下,相当于 - ($ = $,$,$,$,$,$,$,$,$,$,$) ; i ++){
pre> for(i = 1,j = 0; i< ; 10; i ++){
j + = i;
System.out.println(i);
System.out.println(i);
for()
do_something;
do_something_else;
j + = i;
}
System.out.println(i);
因此整个循环都是迭代的,从那以后i == 10的值,就是你的在第二种情况下输出。
在第一种情况下,非常明显的是每次迭代打印值1至9(小于10):对于(i = 1,j = 0; i $ b
j + = i;
System.out.println(i);
}
I wonder why this two following codes give different results;
for(i = 1, j = 0; i < 10; i++) {
j += i;
System.out.println(i);
}
This one gives the numbers between 1 included and 10 excluded.
for(i = 1, j = 0; i < 10; i++)
j += i;
System.out.println(i);
However this one gives 10. I could not get the logic of this;
for()
do_something;
do_something_else;
That is because the default scope of an iteration is the only following line after it, in your case something equivalent to -
for(i=1, j=0;i<10;i++) {
j += i;
}
System.out.println(i);
Hence the entire loop is iterated and since after that the value of i==10, that is your output in the second case.
In the first case, it's pretty obvious that the value is printed with each iteration and hence 1 to 9(less than 10) :
for(i=1, j=0;i<10;i++){
j += i;
System.out.println(i);
}
这篇关于for循环没有在java中的大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!