簡體   English   中英

模數行為 -1 % 3 (C++)

[英]Modulus Behavior -1 % 3 (C++)

if (currIndex < 0) {

            cout << currIndex << " % " << array.size() << endl;

            currIndex = currIndex % array.size();

            cout << currIndex << endl;
}

Output:

-1 % 3
0

C++ 中的 -1 % 3 = -1 那么為什么返回 0 呢?

完整片段: https://ideone.com/leWqhi

size() 返回無符號 integer 類型,因此此計算是通過將 -1 轉換為無符號並執行無符號模來完成的。

將 size() 轉換為簽名的 integer 類型以獲得正確的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM