簡體   English   中英

如何使用模運算符遞增和遞減整數

[英]How can I increment and decrement an integer with the modulo operator

我正在嘗試根據點擊增加一個整數。 點擊如何發生並不重要,所以我會堅持邏輯。 我在 Java 中這樣做,但邏輯應該是一樣的。

int index = 0;

// then within the click event
//arrySize holds the size() of an ArrayList which is 10

index = (index + 1) % arrySize;

有了這個邏輯,每次用戶點擊, index都會增加1。然后它對arrySize的模導致indexindex匹配arrySize時回到0

(10 % 10 會使索引回到 0)這很好,因為它有點像從 0 到 10 然后回到 0 並且永遠不會超過 10 的循環。

我正在嘗試執行相同的邏輯但是向后,根據點擊數字將遞減並達到 0 然后返回到arrySize而不是-1

我怎樣才能實現這個邏輯?

(index + arraySize - 1) % arraySize

做你想做的事。

從 Java 8 開始,您可以使用Math.floorMod(x, y)方法。 引用其 Javadoc(強調我的):

floor 模數是x - (floorDiv(x, y) * y)與除數y具有相同的符號,並且在-abs(y) < r < +abs(y)的范圍內。

System.out.println(Math.floorMod(-1, 5)); // prints 4

所以你將擁有:

index = Math.floorMod(index - 1, arrySize);

您不能直接使用-1 % 5 ,因為這將根據運算符%對負數的運算方式輸出-1

index = arraySize - ((index + 1) % arrySize)

如果您想要基於 1 的索引,請使用此選項。 例如,如果您想倒退到 1 是一月的月份。

int previous = ((index - 1 - arraySize) % arraySize) + arraySize

結果

index    previous
1        12
2        1
3        2
4        3
5        4
6        5
7        6
8        7
9        8
10        9
11        10
12        11

示例小提琴

暫無
暫無

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

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