xcode rand() 似乎不是那么随机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10560828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rand() doesn't seem to be so random
提问by Talon
Here is how i'm creating the int:
这是我创建 int 的方式:
int randNumber = rand() % 4;
NSLog(@"%d", randNumber);
However every time I launch the app the number is the same, no matter what.
然而,每次我启动应用程序时,数字都是相同的,无论如何。
I created a button and attached an action to it that re-initializes the random number and logs the new number out and then it generates a random number, but on App launch the random number is always the same (i've launched it over 20 times).
我创建了一个按钮并附加了一个操作,重新初始化随机数并记录新数字,然后它生成一个随机数,但在应用程序启动时随机数总是相同的(我已经启动了 20次)。
Any idea why on app launch the random number is always the same?
知道为什么在应用程序启动时随机数总是相同的吗?
回答by Abby
Try using arc4random()
, which doesn't require a seed
尝试使用arc4random()
,它不需要种子
回答by Oleksi
You need to specify a different seed every time your run the program. Given a seed, the random number generator generates a set of numbers. The same seed will produce the same set of numbers. To get a different set, you need a different seed.
每次运行程序时都需要指定不同的种子。给定一个种子,随机数生成器生成一组数字。相同的种子将产生相同的一组数字。要获得不同的集合,您需要不同的种子。
Take a look at this for some guidance: Generating random numbers in Objective-C
看看这个以获得一些指导:在 Objective-C 中生成随机数
回答by Tiago Peczenyj
rand() is a pseudo random number generator. it uses a seed and produce the exactly sequence for each seed.
rand() 是一个伪随机数生成器。它使用一个种子并为每个种子产生精确的序列。
If you do this in the begin of the program
如果你在程序开始时这样做
srand(time(NULL));
Will works
会起作用
回答by dj2
You have to call srand(unsigned int seed); to seed the rand function. If you don't call srand it will be seeded with 1 every time.
你必须调用 srand(unsigned int seed); 播种 rand 函数。如果你不调用 srand ,它每次都会被播种 1。