为什么输出是25?
// CODE 1
public class YourClassNameHere {
public static void main(String[] args) {
int x = 8;
System.out.print(x + x++ + x);
}
}
嗨!
我知道上面的代码将打印 25。但是,我想澄清一下 x++ 将如何使该语句成为 8 + 9 + 8 = 25。
如果我们只打印 x++,则会打印 8,而由于后增量,x 在内存中将是 9。
// CODE 2
public class YourClassNameHere {
public static void main(String[] args) {
int x = 8;
System.out.print(x++);
}
}
但是为什么代码1最终变成了9呢?
预先感谢您的时间和解释!
最佳答案
这里有一个好方法来测试等于 25 的原因是因为第三个 x
等于 9。
public class Main {
public static void main(String[] args) {
int x = 8;
System.out.println(printPassThrough(x, "first") + printPassThrough(x++, "second") + printPassThrough(x, "third"));
}
private static int printPassThrough(int x, String name) {
System.out.println(x + " => " + name);
return x;
}
}
结果
8 => first
8 => second
9 => third
25
关于Java:操作顺序、增量后澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68925647/