我对增量和减量运算符有疑问。我无法理解为什么java会给出这些输出。
x = 5; y = 10;
System.out.println(z = y *= x++); // output is 50
x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46
x = 5;
System.out.println( x++*x); // output is 30
x = 5;
System.out.println( x*x++); // output is 25
例如,在第二个println函数中,y在不增加1的情况下被乘法,在第三个函数中,x与x + 1相乘。因为我知道一元递增和一元递减运算符比算术运算符具有更高的优先级,所以为什么第二个运算符计算而不增加1(y ++ * x = 3 * 2 = 6那里为什么不(y + 1)* x = 8?
答案 0 :(得分:5)
要理解的东西:
后增量运算符(变量名后面的++
)返回变量的旧值,然后递增变量。因此,如果x
为5
,则表达式x++
的计算结果为5
,副作用为x
设置为6
。
这个有点特别:
x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46
请注意,此处正在使用字符串连接。它会打印Result =
,然后是4
,这是z
的值,然后是y++ * x
的值6
。 46
不是一个数字,而是来自两个表达式的4
和6
。
答案 1 :(得分:1)
x = 5; y = 10;
System.out.println(z = y *= x++); // output is 50 -->z=y=y*x i.e, z=y=10*5 (now, after evaluation of the expression, x is incremented to 6)
x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46 --> from Right to left . y++ * x happens first..So, 3 * 2 = 6 (now, y will be incremented to 4) then "Result = " +z (String) + number (y++ * z) will be concatenated as Strings.
x = 5;
System.out.println( x++*x); // output is 30 --> 5 * (5+1 i.e, x is already incremented to 6 when you do x++ so its like 5 *6 )
x = 5;
System.out.println( x*x++); // output is 25 -- > 5 * 5 (x will be incremented now)
答案 2 :(得分:0)
postfix - ++
表示变量以其当前值计算,并且在计算了周围表达式之后,变量会递增。
答案 3 :(得分:0)
y ++将在代码后添加1到y。 ++ y将在代码之前添加1到y。
答案 4 :(得分:0)
它们的优先级高于二元运算符,但它们的计算结果为“x”。后递增的副作用不是优先级的一部分。
答案 5 :(得分:0)
因为首先评估y++
y
,然后递增。
相反,使用++y
,增量会在评估之前发生。
答案 6 :(得分:0)
您的第一个表达式z = y *= x++
等于:
z=y=y*x;
x++;
你的第二个表达式+ z + y++ * x
等同于:
z + ""+ (y*x) // here z = 4 and y*x is 6 which gives us 46.
同样地,你可以找到第3和第4个表达。
答案 7 :(得分:0)
我建议阅读本教程,我认为会对使用情况有所了解 - > Java operators.
让我们把它分块:
x = 5; y = 10;
System.out.println(z = y *= x++);
在上面的代码中,你有一个z的赋值给y * = x ++的结果;这意味着y = y * x ++。现在,x ++将在乘法完成后进行评估。如果你以前想要它,你应该使用++ x。
x = 2; y = 3; z = 4;
System.out.println("Result = "+ z + y++ * x); // output is Result = 46
在这种情况下,您将字符串与上面的值连接起来;乘法将是第一个,之后是加法,并且只在最后评估后增量。
其余示例与上述示例类似。运算符优先级是上面应用的规则,您可以使用此表来查看它们的计算顺序:Operator Precedence