Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

random

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.

like image 528
Sumit M Asok Avatar asked Nov 23 '09 14:11

Sumit M Asok


1 Answers

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.

like image 129
Yacoby Avatar answered Sep 25 '22 09:09

Yacoby