Lol*_*ans 7 java logic operators
所以我正在测试运营商,因为我用java帮助我的朋友,我偶然发现了一个奇怪的编程顺序.运行以下代码时发生了什么
public static void main(String[] args) {
int B = 6;
//First console print out
System.out.println(B+=++B);
System.out.println(B);
B = 6;
//Second Console print out
System.out.println(B+=B++);
System.out.println(B);
}
Run Code Online (Sandbox Code Playgroud)
以下代码的输出是
13
13
12
12
Run Code Online (Sandbox Code Playgroud)
是什么原因导致第二个控制台B数学输出= 12时它自己加6,然后是++(这是+1)
这里的区别在于增量运算符.
在这种情况下B += ++B
,B增加到7并加到它的旧自己(6)以达到13.
在这种情况下B += B++
,B被添加到自身,给出12,然后执行++并将结果存储在B中,但计算结果然后存储在B中的++上.因此给出12作为输出.
ACTION EFFECT NOTES
---------- ------ -----
B = 6 B = 6
B += (++B) B += 7 // B is incremented and the value is returned
B B = 13
B = 6 B = 6
B += (B++) B += 6 // The current value of B is the result of (B++) and B is
// incremented *after* the (B++) expression; however, the
// assignment to B (+=) happens after the (++) but it does
// not re-read B and thereby covers up the post increment.
B B = 12
Run Code Online (Sandbox Code Playgroud)