generating random values in iPhone

前端 未结 6 924
Happy的楠姐
Happy的楠姐 2020-12-20 00:18

I have used rand(). But it gives a specific value even after I restart application.

I have implemented following in my application.

- (void)viewDidLo         


        
相关标签:
6条回答
  • 2020-12-20 01:08

    use this code, only for Integer random values

    #define random(min,max) ((arc4random() % (max-min+1)) + min)
    

    testing

    for (int i = 0; i < 500; i++) {
        NSLog(@"rand is %d", random(-100,100));
    }
    
    0 讨论(0)
  • 2020-12-20 01:13

    Use the following line before random()

    srand(time(NULL));

    0 讨论(0)
  • 2020-12-20 01:14

    arc4random() is a built-in function that does not require seeding (and so therefore does not produce predictable sequences that can be generated by using a seed), and it conveniently returns integers. I never use anything else.

    0 讨论(0)
  • 2020-12-20 01:14

    Random number generators in software will actually give PSEUDORANDOM sequences of values.

    Unless you seed the random number generator with a value from a truly random event, you will always get the same sequence each time you use the software.

    I don't know about your software, but it doesn't look like you're seeding the random number generator, Gcamp is probably on the right track.

    0 讨论(0)
  • 2020-12-20 01:14

    I would do it like this:

    landscape:

    - (void)viewDidLoad {
    [super viewDidLoad];
    
    
    int x = arc4random()%480;
    int y = arc4random()%320;
    
    lblT.center=CGPointMake(x,y);
    }
    

    not landscape:

     - (void)viewDidLoad {
        [super viewDidLoad];
    
    
        int x = arc4random()%320;
        int y = arc4random()%480;
    
        lblT.center=CGPointMake(x,y);
        }
    
    0 讨论(0)
  • 2020-12-20 01:18

    Since you are using random() and not rand() you should seed the random generator with this bit of code...

    srandomdev();

    0 讨论(0)
提交回复
热议问题