如何在 iOS 上生成随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/510367/
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
How do I generate random numbers on iOS?
提问by user21293
What is the best way to generate random numbers using Objective-C on iOS?
If I use (int)((double) rand() / ((double)(RAND_MAX) + (double) 1) * 5.0)
to generate a number from 0 to 4, every time I start the program on the iPhone it generates the same numbers to start off with.
在 iOS 上使用 Objective-C 生成随机数的最佳方法是什么?
如果我习惯于(int)((double) rand() / ((double)(RAND_MAX) + (double) 1) * 5.0)
生成一个从 0 到 4 的数字,每次我在 iPhone 上启动该程序时,它都会生成相同的数字来开始。
回答by newtonapple
There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):
StackOverFlow 上有一个非常相似的问题。这是更好的解决方案之一(无需播种):
int r = arc4random() % 5;
回答by Andy Jacobs
i use
我用
#define RANDOM_SEED() srandom(time(NULL))
#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))
so you can give a min and max
所以你可以给出一个最小值和最大值
回答by Niyaz
You should seed the random number generator with the current time.
您应该使用当前时间为随机数生成器设置种子。
srand(time(0));
回答by Niyaz
How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().
你需要多随机?如果你想要足够随机的加密,那么使用 SecRandomCopyBytes()。
回答by vava
Call srand()
at the start of your program, it'll reseed random number generator
srand()
在程序开始时调用,它会重新设置随机数生成器的种子
回答by Himanshu padia
Simple function for random number generation:
随机数生成的简单函数:
int r = arc4random() % 42; // generate number up to 42 (limit)