随机数函数哑火
问题描述:
我有一个需要从1-100的随机整数一个非常简单的iPhone应用程序。
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];
}
问题是,如果我preSS按钮很快,有时则不会显示一个新的随机数。
The problem is, if I press the button quickly, sometimes it won't display a new random number.
答
问题是你与时间
播种。
时间
仅每秒更新一次,所以如果你在一秒内点击它,你会播种发生器用相同的号码,这意味着你会得到的相同的编号。
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.