xcode 在 iPhone 中生成随机值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1436217/
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
generating random values in iPhone
提问by Sagar R. Kothari
I have used rand(). But it gives a specific value even after I restart application.
我用过 rand()。但即使在我重新启动应用程序后,它也会给出一个特定的值。
I have implemented following in my application.
我在我的应用程序中实现了以下内容。
- (void)viewDidLoad {
[super viewDidLoad];
int x,y;
x=random() % 480; y=random() % 300;
lblT.center=CGPointMake(x,y); // my label lblT
}
Try to implement in your application, and launch application. After restarting application, you will find that label will be on specific value.
尝试在您的应用程序中实现,并启动应用程序。重新启动应用程序后,您会发现该标签将显示在特定值上。
回答by Dave DeLong
arc4random()
is a built-in function that does not require seeding (and so therefore does not produce predictable sequences that can be generated by using a seed), and it conveniently returns integers. I never use anything else.
arc4random()
是一个不需要种子的内置函数(因此不会产生可以通过使用种子生成的可预测序列),并且它可以方便地返回整数。我从不使用其他任何东西。
回答by gcamp
Use the following line before random()
在 random() 之前使用以下行
srand(time(NULL));
srand(time(NULL));
回答by pavium
Random number generators in software will actually give PSEUDORANDOM sequences of values.
软件中的随机数生成器实际上会给出值的伪随机序列。
Unless you seed the random number generator with a value from a truly random event, you will always get the same sequence each time you use the software.
除非您使用来自真正随机事件的值作为随机数生成器的种子,否则每次使用该软件时您将始终获得相同的序列。
I don't know about your software, but it doesn't look like you're seeding the random number generator, Gcampis probably on the right track.
我不知道你的软件,但看起来你不是在播种随机数生成器,Gcamp可能走在正确的轨道上。
回答by probablyCorey
Since you are using random()and not rand()you should seed the random generator with this bit of code...
由于您使用的是random()而不是rand() ,因此您应该使用这段代码为随机生成器提供种子...
srandomdev();
srandomdev();
回答by ASKAPPS
I would do it like this:
我会这样做:
landscape:
风景:
- (void)viewDidLoad {
[super viewDidLoad];
int x = arc4random()%480;
int y = arc4random()%320;
lblT.center=CGPointMake(x,y);
}
not landscape:
不是风景:
- (void)viewDidLoad {
[super viewDidLoad];
int x = arc4random()%320;
int y = arc4random()%480;
lblT.center=CGPointMake(x,y);
}
回答by Alexey Ryabinin
use this code, only for Integerrandom values
使用此代码,仅适用于整数随机值
#define random(min,max) ((arc4random() % (max-min+1)) + min)
testing
测试
for (int i = 0; i < 500; i++) {
NSLog(@"rand is %d", random(-100,100));
}