Alex Rivera | Logout

Turn while loop into math equation?

Asked 2008-12-25T00:12:43.817
16

I have two simple while loops in my program that I feel ought to be math equations, but I'm struggling to convert them:

float a = someValue;
int b = someOtherValue;
int c = 0;

while (a <= -b / 2) {
    c--;
    a += b;
}
while (a >= b / 2) {
    c++;
    a -= b;
}

This code works as-is, but I feel it could be simplified into math equations. The idea here being that this code is taking an offset (someValue) and adjusting a coordinate (c) to minimize the distance from the center of a tile (of size someOtherValue). Any help would be appreciated.

Edit
Report

1 Answer

2
c = (int)((a - (b / 2)) / b + 1);
a -= c * b;

Test case at http://pastebin.com/m1034e639

answered 2008-12-25T00:43:29.233

Your Answer