开发者

Why do I get the same result with rand() every time I compile and run? [duplicate]

This question already has answers here: Why do I always get the same sequence of random numbers with rand()? (12 answers) Closed 8 months ago.

Whenever I run this code, I get a same result.

Program

#include<stdlib.h>

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf("%d\n",i);
 for(i=0;i<10;i++) {
  printf("%d\n",rand());
 }
}

Result:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705

I ran this on mingw. Actually I am learning Objective-C

Please help 开发者_开发百科me.


You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

For example

srand(time(NULL));
rand();//now returns a random number

The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.


You want to initialize the PRNG.

Initialize it once (typically inside main()) with a call to the srand() function.

If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.

srand(1); /* same as default */
srand(42); /* no gain, compared to the line above */

You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.

srand(time(NULL)); /* different pseudo random numbers almost every run */

The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.


Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.


The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.

To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜