gpt4 book ai didi

Java, "a[1] *= a[1] = b[n + 1]"没有按预期工作?

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:34 25 4
gpt4 key购买 nike

如标题所示,我有一个使用临时数组的函数,我想从另一个数组中写入一个值,然后将这两个值与自身相乘。

例子:

float[] a = {0, 0}

a[0] *= a[0] = b[n ];
a[1] *= a[1] = b[n + 1];

我希望上面的代码会执行以下操作:

a[0] = b[n    ];
a[0] *= a[0]; //(aka: a[0] = a[0] * a[0])

a[1] = b[n + 1];
a[1] *= a[1];

虽然这种行为似乎并没有发生什么。相反,它似乎只是将“a”中的原始值乘以“b”中的任何值,如下所示:

a[0] = a[0] * b[n    ];
a[1] = a[1] * b[n + 1];

我一直认为,“=”之后的任何内容都会首先求值,就像您这样做时看到的那样:

float a, b;
a = b = 5;
//"a" and "b" both equal "5" now.

既然如此,那岂不是说明我的原始示例应该有效吗?

谁能解释发生了什么以及为什么这段代码没有按预期工作?

最佳答案

我认为到目前为止的答案是不正确的。发挥作用的是复合表达式的计算,例如 a *= b。简而言之,左侧的值先于右侧计算。来自JLS (强调我的):

At run time, the expression is evaluated in one of two ways.

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[0] *= a[0] = b[n    ];
  1. a[0] 的值被计算并存储在 say tmp
  2. a[0] = b[n] 被评估,给出 b[n] 的值(并改变 a[0] 的值b[n])
  3. tmp * a[0] 计算
  4. 最后一步的结果赋值给a[0]

因此,您得到的实际上是 a[0] *= b[n]

编辑:关于作业的从右到左-评估的混淆:我没有发现 JLS 中使用的术语,恕我直言,这是不正确的(尽管它在 Java 教程中使用)。它被称为 right-**associative* assJLS 关于赋值是这样说的:

There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

关于Java, "a[1] *= a[1] = b[n + 1]"没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49399423/

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