random numbers not so random

c++, random

Solution

You need to call `srand()` once, outside of the randomizer function. Otherwise, you re-seed the random number generator each time with the exact same time value, producing the same initial "random" value.

Problem

I have a method in a class as follows... ``` class foo{ int bar::randomNum10to50(){ srand (time(NULL)); int random10to50 = rand()%50+10; return random10to50; } } ``` However when I call it from main (just to check the output, because i wasn't getting the behaviour from the program I expected) like so.... ``` foo create; for (int i=0; i<20;i++){ cout<<create.randomNum10to50()<<endl; } ``` it's exactly the same number every time it's run (ie, 9,9,9,9,9,....; next run: 43,43,43,43,.....) I don't know what is going wrong. The code runs very quickly so I was thinking that MIGHT be the issue but I don't see why there wouldn't be a difference even slightly between the 20 iterations of it. Any thoughts are appreciated! Thanks!

Original source