Random number function is misfiring

2019-01-20 20:46发布

问题:

I have a very simple iPhone app that requires a random integer from 1-100.

I have a button that calls the random number function then displays it.

-(IBAction)buttonReleased;
{
    srandom(time(NULL)); 
    int theNum = random() % 100 + 1;
    numberDisplay.text = [NSString stringWithFormat:@"%d", theNum];
}

The problem is, if I press the button quickly, sometimes it won't display a new random number.

回答1:

The problem is you're seeding with time.

time is only updated every second, so if you click it within the second, you will seed the generator with the same number, which means you'll be getting the same number.

You should only be seeding once, at the start of the application.



回答2:

srandom(time(NULL)); 

Don't do that every time you generate a random number. Do it once, when your application starts.

Reason: Every time you call srandom() with a specific number, you'll get the same sequence of pseudo-random numbers from random(). So if you call your function twice in the same second, you'll get the same number.