【发布时间】:2012-04-25 08:53:28
【问题描述】:
可能重复:
why do i always get the same sequence of random numbers with rand()?
我感到困惑的是,即使使用不同的程序(在同一台机器上)来运行/编译,并且在取消函数(之前和之后)的值之后.. 没关系.. 每次我运行它时,我都会得到相同的“随机”数字。我发誓这不是它应该如何工作的......我将尽可能简单地说明......
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
int rPrimitive = 0; rPrimitive = 1 + rand() % 50;
NSNumber *rObject = nil; rObject = [NSNumber numberWithInt:rand() % 10];
NSLog(@"%i %@", rPrimitive, rObject);
rPrimitive = 0; rObject = nil;
NSLog(@"%i %@", rPrimitive, rObject);
return 0;
}
在 TextMate 中运行:
i686-apple-darwin11-llvm-gcc-4.2
8 9
0 (null)
在 CodeRunner 中运行它:
i686-apple-darwin11-llvm-gcc-4.2
8 9
0 (null)
如果您愿意,可以运行一百万次。你可以猜到它永远是什么。为什么会这样?为什么哦为什么这是“它是这样的”?
【问题讨论】:
-
我的问题确实与以下事实有关,即这些结果跨越操作系统/内存的逻辑划分,并且尽管将 null 分配给值,但它们仍然发生,而不是
rand本身。 -
@alexgray 这只是意味着不同的操作系统使用相同的 PRNG,这并不意外。设置 null 不会改变任何东西,因为这是
rand的预期行为,而不是内存错误。 -
请不要删除自动生成的重复链接。您可以标记此问题以引起版主注意,或在 Meta Stack Exchange 上提出问题,如果您认为应该重新打开它。
标签: objective-c c random