2017-10-28 104 views
-1

我會輸入向量:{6501,6828,6963,7036,7422,7674,8146,8468,8704,8717,9170 ,9359,9719,9895,9896,9913,9962,154,293,334,492,1323,1479,1539,1727,1870,1943,2383,2392,2996,3282,3812,3903,4465,4605,4665,4772,4828,5142 ,5437,5448,5668,5706,5725,6300,6335};爲什麼操作「>> 1」與C++中的int數據不是「/ 2」

如果我用下面的函數中的代碼計算「Mid」,結果是154,但是當我用「Mid = Left +(Right-Left)>> 1」計算「Mid」時,結果將會是1479. 我不明白髮生了什麼?爲什麼這兩種方式輸出不同的結果?

的功能是:

int minNumberInRotateArray(vector<int> rotateArray) { 
     if (!rotateArray.size()) return 0; 
     int Left = 0, Right = rotateArray.size() - 1; 
     int Mid = Left + (Right - Left)/2; 
     while (Left < Right) 
     { 
      if (rotateArray[Left] < rotateArray[Mid]) Left = Mid; 
      else if (rotateArray[Right] > rotateArray[Mid]) Right = Mid; 
      else return rotateArray[Right]; 
      Mid = Left + (Right - Left)/2; 
     } 

     return 0; 
    } 
+0

什麼結果是正確的? – xanoetux

+0

你嘗試過Mid = Left +((Right-Left)>> 1)'?恐怕這是運營商優先考慮的問題。 – user0042

+0

你有沒有試過:'(-1 >> 10)'? –

回答

3

操作>>具有比+較低的優先級值。

這意味着a + (b - c) >> d實際上被解釋爲(a + (b - c)) >> d而不是您所期望的a + ((b - c) >> 1)

您可以在此處查看運營商優先級別表: http://en.cppreference.com/w/cpp/language/operator_precedence

我建議使用/,因爲良好的編譯器會優化兩個使用班次的分歧,而且它更清楚您正在嘗試做什麼。 或者,您可以考慮使用括號。

2

您的問題與運營商優先權。您應該使用Left + ((Right - Left) >> 1)。但是,如果你想知道什麼時候>> 1/2不同,想想-1

  • -1/2 == 0
  • -1 >> 1 == -1

,他們是編譯器不只是優化/ 2>> 1不同手段的事實。這是GCC生成劃分:

mov %edi,%eax 
shr $0x1f,%eax 
add %edi,%eax 
sar %eax 

和不斷變化的產生:

sar %eax 
相關問題