为什么这个随机数有时会被设置为-1?

gar*_*uan 1 iphone cocoa objective-c

每隔一段时间,以下出现-1

int randomIndex = random() % [directionsArray count] - 1;
Run Code Online (Sandbox Code Playgroud)

此类的init方法是创建并srand()调用directionsArray的位置.看起来像这样

- (id) initSprite
{
    if ( ( self = [super initSprite] ) ) {

        speed = 1;

        directionsArray = [[NSArray arrayWithObjects:STRING_CONSTANT, STRING_CONSTANT, nil] retain];
        srand(time(NULL));
        [self pickRandomDirection];


    }
    return self;
}

- (void) pickRandomDirection
{
    int randomIndex = random() % [directionsArray count] - 1; // This sometimes comes out as -1??
}
Run Code Online (Sandbox Code Playgroud)

目前,我正在使用它来解决它abs(randomIndex),但这是作弊,我应该知道将来发生了什么.

nos*_*nos 6

因为0 - 1等于-1.

    random() % [directionsArray count] - 1;
Run Code Online (Sandbox Code Playgroud)

What if random() returns 0 here ? You get 0%[directionsArray count] - 1; which is -1, since % has precedence over -

Perhaps you want random() % ([directionsArray count] - 1);


Jon*_*off 5

%优先于-1吗?如果确实如此,则当余数为0时,1将导致负1.