2017-03-03 96 views
0

我尝试使用下面的代码来生成随机负NSInteger的,生成一个随机的负NSInteger的

+ (NSInteger)getNegativeRandomNumber { 
    uint32_t random = arc4random_uniform(2147483647); // where 2147483647 is the max 32-bit positive value returned by random function 
    return (NSInteger)(-1 * random); // convert the positive into negative number 
} 

但有时这些代码让我的正数。你看到这个代码的任何问题?

+2

'回报 - (NSInteger的)随机的;'。这个问题是由于64位和32位体系结构,而'NSInteger'具有不同的定义。你正在做' - 'sutff,随机和铸造。 – Larme

回答

2

你得到负数与

return -(NSInteger)random; 

您需要第一投射到一个符号的类型。

+0

可能很好解释为什么这是这种情况(即否定一个无符号数将返回一个无符号数,所以你需要先转换为signed)。 –

0

这必将有助于....

-(int) generateRandomNumberWithlowerBound:(int)0 
           upperBound:(int) 2147483647 
{ 
    int rndValue = lowerBound + arc4random() % (upperBound - lowerBound); 
    return -(NSInteger)(rndValue); 
}