java - 基本增量

标签 java loops for-loop increment

我知道这是一个非常基本的问题,但是。

我理解背后的概念。 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?

++ii++ 之间的区别仅在它用作更大表达式的一部分时才有意义,例如

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/

相关文章:

java - 使用Java循环制作图案

java - 用 Java 保存文件

java - 如何在表格行中添加按钮

java - 将 Spring MVC 与内联 PHP 混合

javascript - jQuery 遍历一个对象数组

Java将哨兵值作为数组输入

c++ - 像这样的 for 循环被认为是不好的做法吗?

java - 监视 Java 的系统资源使用

Python:else内部的while循环

python - 神秘的 IndexError - 非常基本的问题(Python)