gpt4 book ai didi

java - 它的正确答案是 22。但我得到 24。我哪里错了?我最后评估赋值运算符 += 因为它具有最低的优先级

转载 作者:行者123 更新时间:2023-12-02 18:35:16 25 4
gpt4 key购买 nike

class Output
{
public static void main (String[] args)
{
int a = 5;

a += 5+ (++a) + (a++);
System.out.print(a);
}
}

评价:

a += 5 + (++a) + (a++)

=> a+= 5 + 6 + (a++) [++a :increment value of a and then use it. So:increment a = 6, then use a=6]

=> a+= 5 + 6 + 6 [a++ :use and then increment value of a. So: use a=6, then increment a=7]

=> a+= 11 + 6

=> a+= 17

=> a = a+17

=> a = 7 + 17

=> a = 24

最佳答案

+= 运算符与所有复合运算符一样,首先 计算左侧的变量,然后再计算所有其他操作数,并在实际执行任何操作之前。这是由 JLS, Section 15.26.2 指定的:

If the left-hand operand expression is not an array access expression, then:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

(大胆强调我的)

这意味着 a a++ 左侧被评估(并保存)为 5++a 在右侧计算。右侧的计算结果为 17,但由于左侧仍为 5,因此总和为 22,而不是 24.

关于java - 它的正确答案是 22。但我得到 24。我哪里错了?我最后评估赋值运算符 += 因为它具有最低的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68854192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com