生成随机数
代码:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//Objective-C 没有提供相关的函数生成随机数,不过C供了rand(), srand(), random(), srandom(), arc4random()几个函数。
//其中arc4random()不用seed
//生成0到100的随机数
int x = arc4random() % 100;
NSLog(@"0~100 = %@",[NSNumber numberWithInt:x]);
//生成500到1000的随机数
int y = (arc4random() % 501) + 500;
NSLog(@"500~1000 = %@",[NSNumber numberWithInt:y]);
[pool drain];
return 0;
}
结果:
[Switching to process 1637 thread 0x0] 2011-05-10 09:54:03.008 demo02[1637:903] 0~100 = 6 2011-05-10 09:54:03.011 demo02[1637:903] 500~1000 = 837

浙公网安备 33010602011771号