0

I am generating random numbers by using srand(time(NULL)). Any idea why it always gives just even random numbers? In my case its giving so. Please help i need odd numbers too. I need the set of 0s, 1s. for eg : {1,1,0,0,1,0,0,0,1,1,0}

Arush Kamboj
  • 673
  • 3
  • 10
  • 20

2 Answers2

3

Call

srand(time(NULL));

only one time at the beginning of your program, it "shuffles" the random sequence.

Then call

rand();

And it will return a number in the range 0 to RAND_MAX.

If you want only 0 or 1 then you can try with

int n = rand() % 2;

or

int n = rand() & 0x01;
dash1e
  • 7,677
  • 1
  • 30
  • 35
0

Think of initializing the PRNG like initializing a variable ... You don't do

// pseudo-code
// print numbers from 1 to 10
do 10 times
    number_to_print = 1
    print number_to_print
    number_to_print++
end loop

Likewise, srand() should only be called once per program run.

call srand() // initialize PRNG
loop
    rand()
end loop
pmg
  • 106,608
  • 13
  • 126
  • 198