为什么我一直得到相同的随机值?

Ale*_*ray 0 c random objective-c

可能重复:
为什么我总是使用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;           
}
Run Code Online (Sandbox Code Playgroud)

在TextMate中运行它:

i686-apple-darwin11-llvm-gcc-4.2
8  9
0  (null)
Run Code Online (Sandbox Code Playgroud)

在CodeRunner中运行它:

i686-apple-darwin11-llvm-gcc-4.2
8  9
0  (null)
Run Code Online (Sandbox Code Playgroud)

如果你愿意,可以运行一百万次.你可以猜到它将永远是什么.为什么会这样?为什么这就是"它是怎么回事"?

Qua*_*nic 6

这就是为什么(来自rand手册页):

   If no seed value is provided,  the  rand()  function  is  automatically
   seeded with a value of 1.
Run Code Online (Sandbox Code Playgroud)

由于它总是以相同的数字播种,因此它将始终产生相同的数字序列.为了让它在每次运行时生成不同的序列,每次运行时都需要使用不同的种子.您可以使用srand()设置种子.

  • 请注意,常见模式是`srand(time(NULL))`,以便程序的连续运行获得不同的种子. (2认同)