Search code examples
crandom

Random Number: either 0 or 1


I've this code:

srand(time(NULL));
int n = rand() % 1 + 0;
printf("%d\n", n);

But, if i put it (notsrand(time(NULL))) in a loop for e.g., it generates only a sequence of 0. There is another implementation for the random numbers between 0 and 1 or i've forgot something?


Solution

  • If you meant 0 or 1, your % makes some sense, but you meant % 2 (or & 1). Of course, the + 0 is still rather pointless, no idea what you're aiming for there. For an integer result of 0 or 1, just do:

    const randomBit = rand() % 2;
    

    The compiler will probably "strength-reduce" that to:

    const randomBit = rand() & 1;
    

    Also, make sure you only call srand() once in your program or it won't have the effect you expect.