Java Arithmetic - Using MOD (%)

S

Steven Davies

I'm trying to iterate over an array, copying objects from one array into
another and "wrap around" over the boundary of the initial array, but I
have a problem:

I'm using the % operator to try and get the value to wrap around, but it
keeps jumping to negative numbers.

Here's a code snippet:
for (int x = 0; x < (sightDist * 2 + 1); x++) {
for (int y = 0; y < (sightDist * 2 + 1); y++) {
visibleArray[x][y] = theTiles[oldX][oldY];
oldY = (oldY + 1) % 100;
}
oldY = (oldY - (sightDist * 2 + 1)) % 100;
oldX = (oldX + 1) % 100;
}

Does anyone have any idea why the statements at the bottom don't seem to
mod the number properly? Any more details you need, ask me :)

(oldX and oldY are definitely positive before this is executed, the
array called theTiles is 100 by 100.)

Thanks,
Steven Davies
 
Y

Yamin

a negative return from a mod is perfectly valid mathemetically.
99 % 100 is the same as -1 % 100. I haven't done any research into
Java's implementation of mod, but perhaps it is returning that negative
version. Assuming this is the case...you can get the mod you want by:
value = equation % 100;
if( value < 0) value= value + 100;

Yamin
 
S

Steven Davies

Yamin said:
a negative return from a mod is perfectly valid mathemetically.
99 % 100 is the same as -1 % 100. I haven't done any research into
Java's implementation of mod, but perhaps it is returning that negative
version. Assuming this is the case...you can get the mod you want by:
value = equation % 100;
if( value < 0) value= value + 100;

Yamin

Yeah, I read the Java language spec and indeed if you do z = x % y and x
is negative, so is your result. A quick z+=array.length worked a treat :)

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top