-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
有誰知道爲什麼下面的代碼在Python中沒有相同的結果? 爲什麼我需要括號才能得到正確的結果?python模爲什麼是1-4%5不一樣(1-4)%5
#example 1
print 1-4 %5
outcome: -3
#example 2
print (1-4)%5
outcome: 2
這是由於operator precedence。 MOD(%
)優先於-
,所以:
1-4 % 5 == 1 - (4 % 5) == 1 - 4 == -3
但
(1-4) % 5 == -3 % 5 == 2
Python的算符優先具有減去僅僅比模量
http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
*, /, % Multiplication, division, remainder
+, - Addition, subtraction
[運算符優先級]下(https://docs.python.org/2/reference/expressions.html#oper ATOR優先級)。就像'1 - 4 * 5'和'(1 - 4)* 5'。 – grc 2014-09-27 02:06:55
非常感謝您的快速響應!我想我在數學上不是那麼棒:-) – 2014-09-27 02:09:03