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}
Asked
Active
Viewed 5,823 times
0
-
5Not without seeing the code that you're using. – Oliver Charlesworth Apr 14 '12 at 10:00
-
You're doing something wrong. Please show us your code. – user703016 Apr 14 '12 at 10:00
-
2srand(time(NULL)) is just a seed. Show us your code where the function rand() is assigning numbers. – ScarletAmaranth Apr 14 '12 at 10:00
2 Answers
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