1
int random_var(void);

int main(void)
{
    int i;
    for (i = 1; i <= 50; i++)
        printf("%d\n", random_var());

return 0;
}


int random_var(void)
{
    srand((unsigned) time(NULL));
    return rand() % 2;
}

I am tasked to write a function that returns a random value of 1 or 0 everytime it is called. My code keeps returning a fixed value even though I used a random generator for the seed, why??

12johnny
  • 71
  • 2
  • 8

1 Answers1

1

You need to call srand() only once!

int random_var(void);

int main(void)
{
    int i;
    srand((unsigned) time(NULL));
    for (i = 1; i <= 50; i++)
        printf("%d\n", random_var());

    return 0;
}


int random_var(void)
{
    return rand() % 2;
}

Alternatively (or additionally), as Keith Thompson pointed out, you can try taking higher order bits instead, which may distribute better.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 1
    *Some* implementations of `rand()` will return alternating even and odd numbers. [comp.lang.c FAQ](http://www.c-faq.com} question 13.18. – Keith Thompson Oct 25 '16 at 21:00
  • @KeithThompson, I'd upvote your comment if I hadn't have reached the daily limit today. However, sadly, [some popular implementations won't...](https://ideone.com/ajAD1Y) – StoryTeller - Unslander Monica Oct 25 '16 at 21:01
  • Of course if you re-seed with the same value you'll get the same results. – Keith Thompson Oct 25 '16 at 21:03
  • 2
    To expand on the problem, the OP is calling `srand` which seeded with the time in seconds. The tight `for` loop from 1 to 50 will execute in much less than a second, so `srand` is getting seeded with the same value 50 times. Therefore `rand()` will return the same value 50 times. If you happen to execute this loop during the transition to then next second, `rand` would return a different number, then the new one would be repeated until the loop terminated. – yano Oct 25 '16 at 21:04
  • @yano, you should post that as an answer. It's spot on. – StoryTeller - Unslander Monica Oct 25 '16 at 21:06
  • heh, thought about it, but it would've been the same as your answer .. think it's all covered now – yano Oct 25 '16 at 21:19