Random number function is misfiring

2019-01-20 20:11发布

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.

2条回答
家丑人穷心不美
2楼-- · 2019-01-20 20:42

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.

查看更多
走好不送
3楼-- · 2019-01-20 20:53
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.

查看更多
登录 后发表回答