简体   繁体   English

随机数函数错误

[英]Random number function is misfiring

I have a very simple iPhone app that requires a random integer from 1-100. 我有一个非常简单的iPhone应用程序,需要一个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. 问题是,如果我快速按下按钮,有时它将不会显示新的随机数。

The problem is you're seeding with time . 问题是你在播种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. time仅每秒更新一次,因此,如果您在第二秒内单击它,则会为生成器提供相同的编号,这意味着您将获得相同的编号。

You should only be seeding once, at the start of the application. 在应用程序开始时,您只能播种一次。

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(). 原因:每次使用特定数字调用srandom()时,都会从random()获得相同的伪随机数序列。 So if you call your function twice in the same second, you'll get the same number. 因此,如果您在同一秒内两次调用函数,您将获得相同的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM