英文:
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
。我尝试将 step1
和 step2
内联,期望得到相同的结果,但实际上打印出 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论