0

在像「10-3-2」這樣的表達式中,很容易理解爲什麼 - 和+運算符是關聯的。爲了匹配數學約定,結果是5而不是9。據我所知,結合性意味着某些運營商具有相同的優先級時的順序。爲什麼一元運算符具有關聯性

但是這與一元運算符有什麼關係?我不明白爲什麼一個一元運算符具有關聯性。

注意:這個問題是關於一般的編程,但如果你必須以一種語言相關的方式回答C是首選。

+0

請參閱http://stackoverflow.com/questions/12961351/does-it-make-sense-for-unary-opera要聯想的(不是重複的,因爲這是針對C++的,而且這個解釋看起來並不「太好」,但它似乎仍然「足夠好」) – xanatos

回答

1
**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. 

欲知詳情,請參考下面:

  1. Precedence and Associativity
  2. Assignment, Arithmetic, and Unary Operators(我不是用C語言太多聯繫,但運營商是共同的。)
相關問題