[英]Java Precedence
int x = 1;
System.out.println( x++ + x++ * --x );
The above code prints out "5" but I don't understand how? 上面的代码打印出“ 5”,但我不知道如何? I keep getting zero for the last x which is then multiplied by the second x which is still 0 and then I get 2?
我对最后一个x始终保持零,然后乘以第二个x仍为0,然后得到2? Please help!
请帮忙!
The way the program processes your statement is as follows: 程序处理语句的方式如下:
x = 1;
1 + (increment x) 2 * (increment x)(decrement x) 2 =
1 + 2 * 2 =
1 + 4 =
5
Added: 添加:
If you ask it to print it out for you instead of actually doing the arithmetic, you'll see what the x's actually equal: 如果您要求它为您打印出来而不是实际进行算术运算,则会看到x的实际相等:
int x = 1;
System.out.println(x++ + " + " + x++ + "*" + --x);
Output: 1 + 2*2
输出:
1 + 2*2
It works like this: 它是这样的:
System.out.println( x++ + x++ * --x );
Since the first two are postfix they will not be performed until after a value is already put in. A 1 is put in the first x
then the value is increased to 2. A 2 is put in the second x
and the value is increased to 3. 由于前两个是后缀,它们将不执行,直到已经输入一个值之后为止。将A 1放入第一个
x
然后将该值增加到2。将A 2放入第二个x
并将该值增加到3。
System.out.println( 1 + 2 * --x );
Since the --x
is prefix the operation is done prior to subbing in the value. 由于
--x
是前缀,因此需要先进行操作,然后再求值。 Therefore it would equal 2 and x
would equal 2 again. 因此,它将等于2,
x
将再次等于2。
System.out.println( 1 + 2 * 2 );
After this it works the same as it normally would in math (multiplication before addition). 此后,它的工作原理与数学中的正常工作相同(加法前的乘法)。
public static void main(String[] args) {
int x ;
x = 1;
System.out.println( x++ );
//1
System.out.println( x++ * --x );
//2*--3 = 2*2 = 4
System.out.println( x++ + (x++ * --x ));
//1 + 4 = 5
System.out.println( x++ + x++ * --x );
//1 + 4 = 5
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.