I'm trying to generate random negative NSInteger using the following code,
+ (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
}
But occasionally this code gives me positive numbers. Do you see any issue with this code?
You get negative numbers with
return -(NSInteger)random;
You need first to cast to a signed type.
This will surely help....
-(int) generateRandomNumberWithlowerBound:(int)0
upperBound:(int) 2147483647
{
int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
return -(NSInteger)(rndValue);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.