在像“10 - 3 - 2”这样的表达式中,很容易理解为什么 - 和 + 运算符是关联的。为了匹配数学约定,结果是 5 而不是 9。据我了解,关联性是指某些运算符具有相同优先级时的顺序。
但这与一元运算符有什么关系呢?我不明白为什么一元运算符具有关联性。
注意:这个问题是关于一般编程的,但如果你必须以依赖于语言的方式回答,C 是首选。
在像“10 - 3 - 2”这样的表达式中,很容易理解为什么 - 和 + 运算符是关联的。为了匹配数学约定,结果是 5 而不是 9。据我了解,关联性是指某些运算符具有相同优先级时的顺序。
但这与一元运算符有什么关系呢?我不明白为什么一元运算符具有关联性。
注意:这个问题是关于一般编程的,但如果你必须以依赖于语言的方式回答,C 是首选。
**Arithmetic Operators** (Left-to-Right)
+ Additive operator (a + b)
- Subtraction operator (a - b)
* Multiplication operator (a * b)
/ Division operator (a / b)
% Remainder operator (a % b)
**Unary operators** (Right-to-Left)
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
但是当我们考虑一元时:
a = +1
a= -1
a++
a-- etc
您在这里提到的10 - 3 - 2
内容不会被纳入一元运算。
So the operation will be Left-to-Right. Therefore:
10 - 3 equals 7 then
7 - 2 equals 5
Not as given below (Arithmetic operators always Left-to-Right not Right-to-Left)
3 - 2 = 1 then
10 - 1 = 9 This is absolutely wrong.
有关更多详细信息,请查看以下参考:
- 优先级和关联性
- 赋值、算术和一元运算符(我对 C 语言不太了解。但运算符很常见。)