Java 多个 + 和 - 运算符的优先级

Java precedence for multiple + and - operators

这更像是一个理解Java对算术运算求值的理论问题。由于 +- 具有相同的优先级,我不太明白 Java 如何计算以下表达式(其中有多个 +- 两个操作数之间的运算符)。

public static void main(String[] args) {
    int a = 1;
    int b = 2;
    System.out.println(a+-b);    // results in -1
    System.out.println(a-+b);    // results in -1
    System.out.println(a+-+b);   // results in -1
    System.out.println(a-+-b);   // results in  3
    System.out.println(a-+-+b);  // results in  3
    System.out.println(a+-+-b);  // results in  3
    System.out.println(a-+-+-b); // results in -1
    System.out.println(a+-+-+b); // results in  3
}

来自Java 8 语言规范(§15.8.2):

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.
The binary - operator performs subtraction, producing the difference of two numeric operands.
[...]
Addition is a commutative operation if the operand expressions have no side effects.
Integer addition is associative when the operands are all of the same type.

我还注意到,每次#operators 为偶数时,结果都是相同的,顺序无关紧要。 但是当#operators 为奇数时,这并不一定会影响结果。例如。在下面两个表达式中,-+多了一个,但结果不同。

System.out.println(a-+-b);   // results in 3
System.out.println(a-+-+-b); // results in -1

尽管有所有这些信息,但我仍然看不出其中的模式或运作方式。

我相信 - 符号否定表达式:

int a = 1;
int b = 2;
System.out.println(a+(-b));
System.out.println(a+-b);

同时打印 -1。这是来自 oracle 文档:

Unary minus operator; negates an expression

减号只是改变它后面数字的符号。如果 b 为负数,则 a+-b 将 return 3.

在数学上,你如何评价这个?

a - + - b   

添加一些括号有助于:

a - (+ (-b))

我们可以这样做,因为这不违反优先规则。

然后我们可以开始减少:+ (-b)真的是-b,而a - -b真的是a + b,所以结果是1 + 2 = 3

我们来看第二个:

a - + - + - b
a - (+ (- (+ (-b))))
a - (+ (- (-b)))
a - (+ b)
a - b
1 - 2 = -1

如此简单的数学规则自然起作用。

它是根据你如何用加法和减法进行数学计算来评估的。 在您的示例中,您的所有计算都从较小的数字 a=1 开始,然后在较小的数字和较大的数字 b=2 之间有 -+ 符号。例如,当你做 1 -- 2 时,你正在做 1+2 因为 2 个 - 符号相互抵消变成 1 + 21 - 2 将是 -1 因为 2(更大number 有一个 - 符号,这使它成为负整数,负整数加 1 会增加它的值

这似乎是一道数学题...(- & - = +)、(- & + = -) 和 (+ & + = +)

int a = 1;
int b = 2;
System.out.println(a+-b);    // 1 +(-2) = 1-2 = -1
System.out.println(a-+b);    // 1-(+2) = 1-2 = -1
System.out.println(a+-+b);   // 1+-(+2) = 1-(+2) = 1-2 = 1
System.out.println(a-+-b);   // 1- + (-2) = 1- (-2) = 1+2 =3 
System.out.println(a-+-+b);  // 1 - + - (+2) = 1 - - (+2) = 1-2 = -1
System.out.println(a+-+-b);  // 1+ - + (-2) =1 - + (-2) = 1+2 = 3 
System.out.println(a-+-+-b); // 1-+-+(-2) = 1 - - (-2) = 1 + (-2) = -1
System.out.println(a+-+-+b); // 1 +- +- (+2) = 1 -- (+2) = 1+2 = 3