Mod der negativen Zahl schmilzt mein Gehirn
Ich versuche, eine Ganzzahl zu modifizieren, um eine Array-Position zu erhalten, damit sie eine Schleife durchläuft. Tuni % arrayLength
funktioniert gut für positive Zahlen, aber für negative Zahlen geht alles schief.
4 % 3 == 1
3 % 3 == 0
2 % 3 == 2
1 % 3 == 1
0 % 3 == 0
-1 % 3 == -1
-2 % 3 == -2
-3 % 3 == 0
-4 % 3 == -1
Also brauche ich eine Implementierung von
int GetArrayIndex(int i, int arrayLength)
so dass
GetArrayIndex( 4, 3) == 1
GetArrayIndex( 3, 3) == 0
GetArrayIndex( 2, 3) == 2
GetArrayIndex( 1, 3) == 1
GetArrayIndex( 0, 3) == 0
GetArrayIndex(-1, 3) == 2
GetArrayIndex(-2, 3) == 1
GetArrayIndex(-3, 3) == 0
GetArrayIndex(-4, 3) == 2
Ich habe das schon einmal gemacht, aber aus irgendeinem Grund schmilzt es mein Gehirn heute :(