2014-09-27 59 views
-1

有誰知道爲什麼下面的代碼在Python中沒有相同的結果? 爲什麼我需要括號才能得到正確的結果?python模爲什麼是1-4%5不一樣(1-4)%5

#example 1 
print 1-4 %5 
outcome: -3 

#example 2 
print (1-4)%5 
outcome: 2 
+5

[運算符優先級]下(https://docs.python.org/2/reference/expressions.html#oper ATOR優先級)。就像'1 - 4 * 5'和'(1 - 4)* 5'。 – grc 2014-09-27 02:06:55

+0

非常感謝您的快速響應!我想我在數學上不是那麼棒:-) – 2014-09-27 02:09:03

回答

2

這是由於operator precedence。 MOD(%)優先於-,所以:

1-4 % 5 == 1 - (4 % 5) == 1 - 4 == -3 

(1-4) % 5 == -3 % 5 == 2 
相關問題