-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