[英]Can someone explain why the answer is B? I'm using Java and I don't understand
Which of the following statements are the same? 以下哪项陈述相同?
(I) x -= x + 4 (I)x - = x + 4
(II) x = x + 4 - x (II)x = x + 4 - x
(III) x = x - (x + 4) (III)x = x - (x + 4)
A. (I) and (II) are the same A.(I)和(II)是相同的
B. (I) and (III) are the same B.(I)和(III)是相同的
C. (II) and (III) are the same C.(II)和(III)是相同的
D. (I), (II), and (III) are the same D.(I),(II)和(III)是相同的
x -= y is equivalent to x = x - y
Therefore 因此
x -= x + 4
is equivalent to 相当于
x = x - (x+4)
So assuming (II) x = x - (x + 4)
was supposed to be (III) x = x - (x + 4)
(since you have two options marked as (II)
), (I)
and (III)
are the same. 所以假设(II) x = x - (x + 4)
应该是(III) x = x - (x + 4)
(因为你有两个选项标记为(II)
), (I)
和(III)
是相同的。
It's because of operator precedence. 这是因为运营商的优先权。 Java evaluates that as if it were Java评估它就好像它一样
x -= (x+4) x - =(x + 4)
so it first computes (x+4)
and then subtracts that from x
-- which is what the -
part of -=
means -- and then updates x
, which is what the =
part means. 所以它首先计算(x+4)
和然后减去从x
-这是什么-
的一部分-=
指-然后更新x
,这是什么=
部装置。
-=
operator, 情况(I)根据Java -=
运算符扩展到x = x - (x + 4), Therefore (I) and (III) are the same, which means the answer is (B). 因此(I)和(III)是相同的,这意味着答案是(B)。
-=
is a so called compound assignment. -=
是所谓的复合赋值。
Those are just short-cuts and combine atomic operations. 这些只是捷径,并结合原子操作。
x -= y
stands for x = xy
x -= y
代表x = xy
x += y
stands for x = x+y
x += y
代表x = x+y
x++
stands for x = x+1
x++
代表x = x+1
x--
stands for x = x-1
x--
代表x = x-1
There also are ++x and --x which do the same as x++ / x-- except that they return the value of x before it is incremented / decremented. 还有++ x和--x与x ++ / x--相同,只是它们在递增/递减之前返回x的值。
Official Java tutorial: 官方Java教程:
"You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1." “您还可以将算术运算符与简单赋值运算符组合以创建复合赋值。例如,x + = 1;并且x = x + 1;两者都将x的值递增1。”
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
I think the same works for *=
, /=
and %=
我认为同样适用于*=
, /=
和%=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.