题目来源牛客网上面练习的一道题目:
检查程序,是否存在问题,如果存在指出问题所在,如果不存在,说明输出结果。
package algorithms.com.guan.javajicu;
public class Inc {
public static void main(String[] args) {
Inc inc = new Inc();
int i = 0;
inc.fermin(i);
i= i ++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}
原因是:
-
Java使用了中间缓存变量机制:
i=i++;等同于:
temp=i; (等号右边的i)
i=i+1; (等号右边的i)
i=temp; (等号左边的i)
而i=++i;则等同于:
i=i+1;
temp=i;
i=temp;
public static void main(String[] args) throws InterruptedException {
Inc inc = new Inc();
int i = 0;
i = i++;
System.out.println(i);
i = ++i;
System.out.println(i);
}
public static void main(String[] args) throws InterruptedException {
Inc inc = new Inc();
int i = 0;
int j = i++;
System.out.println("i = "+i +" j = "+j);
j = ++i;
System.out.println("i = "+i +" j = "+j);
}对于j = i++等同于
temp=i;
i=i+1;
j=temp;
对于j = ++i等同于
i=i+1;
temp=i;
j=temp;
本文详细解析了Java中自增运算符的工作原理,通过具体的代码示例解释了前缀和后缀自增的区别,以及它们如何影响变量的值。

489

被折叠的 条评论
为什么被折叠?



