[英]Generating a random negative NSInteger
I'm trying to generate random negative NSInteger using the following code, 我正在尝试使用以下代码生成随机负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
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.