开发者

Different results for the same function

开发者 https://www.devze.com 2023-03-31 13:34 出处:网络
Can someone clarify to me please 开发者_StackOverflow中文版why past2 is NOT negative when this code is run? Even though past is.

Can someone clarify to me please 开发者_StackOverflow中文版why past2 is NOT negative when this code is run? Even though past is.

Thanks.

NSTimeInterval p1 = (arc4random()%600000);
NSTimeInterval past = -p1;
NSTimeInterval past2 = -(arc4random()%600000);


arc4random() returns an unsigned int (u_int32_t), so trying to make it negative is coercing the result to unsigned as well, which is why you're getting a very large positive number instead of a negative number.

If you want to get a negative random result in one call, try:

NSTimeInterval past2 = - (int) (arc4random()%600000);

joe

0

精彩评论

暂无评论...
验证码 换一张
取 消