سؤال

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.

هل كانت مفيدة؟

المحلول

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).

نصائح أخرى

Since arc4random() is always positive:

The arc4random() function returns pseudo-random numbers in the range of 0 to (2**32)-1

[Source]

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?

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top