我知道这是一个非常基本的问题,但是。
我理解背后的概念。 n++、++n、n--、--n。然而
public static void main(String[] args){
int count = 1;
for(int i =1;i<=10;++i){
count = count * i;
System.out.print(count);
}
}
所以它会打印:1 2 3 4 5 6 7 8 9 10。
我的问题是。为什么如果 i 递增为++i 而不是 i 然后被视为 2,而不是 1。安装++i 的点,在它被另一个操作操纵之前递增 i?
最佳答案
Is the point of ++i, to increment i before it's manipulated by another operation?
++i
和 i++
之间的区别仅在它用作更大表达式的一部分时才有意义,例如
int j = ++i; // Increment then use the new value for the assignment
int k = i++; // Increment, but use the old value for the assignment
在这种情况下,操作发生在循环的每次迭代结束时,独立。所以你的循环相当于:
int count = 1;
// Introduce a new scope for i, just like the for loop does
{
// Declaration and initialization
int i = 1;
// Condition
while (i <= 10) {
count = count * i;
System.out.print(count);
// Now comes the final expression in the for loop "header"
++i;
}
}
现在将 ++i
更改为 i++
最后根本不会有什么不同 - 表达式的值不用于任何事情.
关于java - 基本增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11035259/