gpt4 book ai didi

java - 我期望输出为 40,但我得到了 30

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:53 25 4
gpt4 key购买 nike

class Tester {
public static void main(String[] arg) {
byte b=10;
b +=(b<127)?b>-128? b+=10 :0 :5;
System.out.println(b);
}
}

我知道条件被评估为 true 并将控制权交给了 b+=10所以现在逻辑上 b+=b+=10; 将 b 和 10 的值相加,计算结果为 20,分配给 b。现在我无法进一步评估它。

最佳答案

JLS 15.7.1. Evaluate Left-Hand Operand First有一个类似的例子:

If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.

Example 15.7.1-2. Implicit Left-Hand Operand In Operator Of Compound Assigment

In the following program, the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition operator is evaluated, at which point the variable is set to 3.

class Test2 {
public static void main(String[] args) {
int a = 9;
a += (a = 3); // first example
System.out.println(a);
int b = 9;
b = b + (b = 3); // second example
System.out.println(b);
}
}

This program produces the output:

12
12

因此,在您的情况下,b (10) 的原始值被记住并添加到三元条件运算符的结果(即 20,因为 b+= 10 是该表达式的结果),给你 30。

关于java - 我期望输出为 40,但我得到了 30,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38627814/

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