問: Python 計算 -7%4 + 1 與 1 - 7%4 二者計算結果相等嗎?
答: 不等!前者結果為2,后者為-2。
對此,作如下兩點解釋:
1. 首先看一下Python計算的優先級,官方手冊的截圖如下(https://docs.python.org/2/reference/expressions.html#id20):
The following table summarizes the operator precedences in Python, from lowest precedence (least binding) to highest precedence (most binding).
可以看到%的優先級是高於“加、減運算”,而低於“數的正、負級”。
所以-7%4 + 1中先計算的是(-7)%4,
而1-7%4中先計算的是7%4 。
2. 取余計算的原則 —— 余數應該大於0
-7 = (-2)*4 +1,所以-7%4 = 1
7 = 1*4 + 3, 所以7%4 = 3