Reputation: 95518
I'm using arc4random()
to generate numbers in a certain range. However, I will intermittently receive negative numbers. I'm not doing anything strange:
if([aBug x] == -1) {
x = arc4random() % columns;
}
if([aBug y] == -1) {
y = arc4random() % rows;
}
Here, x
and y
sometimes get set to negative values. x
and y
are both of type int
.
Upvotes: 1
Views: 1810
Reputation: 21
I was having the same problem. I have no idea why this fixed it but changing from
(int)arc4Random()%4
to
(int)(arc4Random()%4)
seemed to work for me.
Upvotes: 2
Reputation: 28242
Sounds like you want to declare x and y to be of type u_int32_t
instead of int
. I.e., you should be using unsigned variables instead of signed.
Or, use a signed integer that's larger than 32 bits (e.g., uint64_t
/long long
).
Upvotes: 4
Reputation: 32066
Since arc4random()
is always positive:
The arc4random() function returns pseudo-random numbers in the range of 0 to (2**32)-1
I would have to deduce that columns
or rows
is "arbitrarily" negative. Moding a positive number by a negative number will return a negative number.
What are the data types for rows and columns?
Upvotes: 3