putting a variable in a function and getting a return value

I want to get a random number from this function but idk if I did this function right can you please take a look


int random(int x)
{
srand(static_cast<unsigned int>(time(0)));

int randomN = rand();

x = (randomN % 10) + 1;

return x;
}
If you call srand with the same seed you will get the same sequence of random numbers from rand. That means if your function is called within the same second it will give the same number. You don't want that. What you should do to fix this problem is to call srand at the beginning of the main function and never call it again.
so how should I write a function that will give me a random number each time i put a variable in it?
Peter87 wrote:
What you should do to fix this problem is to call srand at the beginning of the main function and never call it again.
the parameter is useless
Since you're using c++, you should really consider std::random (that is, assuming c++11 is okay). It's a slightly higher learning curve but it's worth it, it lets you choose the right balance between speed and randomness for your application and provides lots of different random distribution functions of different resolutions (note that using modulo biases your distribution toward low numbers, especially if you use modulo large numbers).

http://www.cplusplus.com/reference/random/

The basics are, you declare a generator (that's your balance of performance versus randomness) and provide it to a distribution class (which can provide you whatever random distribution you want over whatever range you want), and then you can use it as much as you want.
Last edited on
Topic archived. No new replies allowed.