两个相同的程序有不同的输出?

huangapple go评论69阅读模式
英文:

Two same programs different outputs?

问题

package com.company;

public class test {
    public static void main(String[] args) {
        int x=5, y=4, z;
        int step1 = (++x + ++y);
        int step2 = (y++ % 2);
        z= step1*step2;
        System.out.println(step1 + "*" + step2);
        System.out.println(z);
    }
}

这个程序打印出 11。我尝试将 step1step2 内联,期望得到相同的结果,但实际上打印出 1

package com.company;

public class test {
    public static void main(String[] args) {
        int x=5, y=4, z;
        z= (++x + ++y) * y++ % 2;
        System.out.println(z);
    }
}

为什么输出结果不同呢?

英文:
package com.company;

public class test {
    public static void main(String[] args) {
        int x=5, y=4, z;
        int step1 = (++x + ++y);
        int step2 = (y++ % 2);
        z= step1*step2;
        System.out.println(step1 + "*" + step2);
        System.out.println(z);
    }
}

This program prints 11. I tried inlining step1 and step2 expecting to get the same result but it prints 1 instead.

package com.company;

public class test {
    public static void main(String[] args) {
        int x=5, y=4, z;
        z= (++x + ++y) * y++ % 2;
        System.out.println(z);
    }
}

Why is the output different?

答案1

得分: 4

我建议你查看一下Java是如何处理运算符优先级的。

要得到与你相同的输出,只需将第二个示例中的代码更改为:

z = (++x + ++y) * (y++ % 2);
英文:

I would suggest you take a look at how java does its operator precedence.

To have your same output, just change your code in the second example to

z = (++x + ++y) * (y++ % 2);

答案2

得分: 1

Your code has problem. In java it's working like this.

   z= ((++x + ++y) * y++) % 2;

calculation are
z = ((6 + 5) * 5) % 2
z = (55) % 2
z = 1

for your expected answer, you need to write

   z= (++x + ++y) * (y++ % 2);

now (z = 11)

英文:

Your code has problem. In java it's working like this.

   z= ((++x + ++y) * y++) % 2;

calculation are

z = ((6 + 5) * 5) % 2

z = (55) % 2

z = 1

for your expected answer, you need to write

   z= (++x + ++y) * (y++ % 2);

now (z = 11)

huangapple
  • 本文由 发表于 2020年10月8日 12:35:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64255860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定