简体   繁体   English

为什么增量运算符不更改Java中变量的值?

[英]Why doesn't the increment operator change the value of variable in java?

I recently wrote snippet code like this 我最近写了这样的代码段

public class TestIncrement {

    public static void main(String[] args){
        double a = 12.4; 
        double b = 5.6; 
        a -=b -=b -= b -= b -= b -= b;
        System.out.println(a);
        a-=b; 
        System.out.println(a); 
    }
}

and the output is: 输出为:

12.4
12.4

Why increment operator not work? 为什么增量运算符不起作用?

-= and all other assignment operators are right-associative. -=和所有其他赋值运算符都是右关联的。 This line: 这行:

a -=b -=b -= b -= b -= b -= b;

doesn't mean "decrease a by the value of b 6 times". 并不意味着“减少a由的值b 6次”。 It means the same as this: 它的含义与此相同:

a -= (b -= (b -= (b -= (b -= (b -= b)))));

which means "decrease b by the value of b , then decrease b by the new value of b , then do that 3 more times, then decrease a by the final value of b ". 这意味着“降低b通过的值b ,则减少b通过的新值b ,则这样做3次以上,则减少a通过的最终值b ”。 b is 0 after the first -= , so the rest of the statement does nothing, as does the b在第一个-=之后为0,因此语句的其余部分不执行任何操作,就像

a-=b;

line. 线。

It does work. 确实有效。 Your b variable is equal to 0. 您的b变量等于0。

If I put parentheses around all that to make it easier to understand, we get this: 如果在所有内容之间加上括号以使其更易于理解,我们将得到:

public class TestIncrement {
    public static void main(String[] args){
        double a = 12.4; 
        double b = 5.6; 
        a -= (b -= (b -= (b -= (b -= (b -= b)))));
        System.out.println(a);
        a -= b; 
        System.out.println(a); 
    }
}

The first b -= b statement sets b to 0 . 第一个b -= b语句将b设置为0 After 0 is subtracted from b 4 more times, the result is still 0 , which obviously leaves the value of a unchanged. 0从减去b 4次以上,结果仍然是0 ,这显然离开的值a不变。 Even if you try again, in the a -= b line, you will still get the same result: 12.4 − 0.0 = 12.4 . 即使再次尝试,在a -= b行中,您仍然会得到相同的结果: 12.4 − 0.0 = 12.4

You could have figured this out on your own, by writing a simpler example. 通过编写一个更简单的示例,您可以自己解决这个问题。

public static void main(String[] args){
    int a = 1;
    int b = 2;
    int c = 3;

    a -= b -= c;

    System.out.println(a + " " + b + " " + c);
}

You'd be surprised to see that the output is 2 -1 3 您会惊讶地看到输出为2 -1 3
This reason is, the above code is equal to: 原因是,上面的代码等于:

public static void main(String[] args){
    int a = 1;
    int b = 2;
    int c = 3;

    b -= c;
    a -= b;

    System.out.println(a + " " + b + " " + c);
}

Don't do spaghetti code. 不要做意大利面条代码。 :( :(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM