Story: Using rand()
function in C++, I can get random numbers, and using %
I can set the range. However, If I also want to add bias, then I also have to add bias to the result. This is too much work to do, so I decided to write my own function to handle this. However I am stuck at one point.
I know that, I have to feed a new sequence(srand(time(NULL))
) each time the program runs, otherwise I will get same numbers all the time.
The obvious way to do this is, to insert srand(time(NULL))
in the main()
function. However, I don't want to do that, I want somehow it gets done automatically when I include my .h
file.
Suppose myFunctions.h
:
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <ctime>
int randint(int start, int end);
and myFunctions.cpp
:
#include "myFunctions.h"
/* [start,end) */
int randint(int start, int end)
{
return (rand() % (end - start)) + start;
}
Now, I am confused where I should add srand()
. If I do it in randint()
definition, I assume, because of the fact that time difference will be too low, time(NULL)
will evaluate the same value for each step of the loop and it will feed the same seed all the time when I want to get random numbers in a very short time, like:
for(int i = 0; i < 50; i++){
std::cout << randint(0, 3) << std::endl;
}
The output is the same number, 50 times. So it confirms my suspicion.
I have tried something like this in my randint()
definition,
int randint(int start, int end)
{
#ifndef SEED
srand(time(NULL));
#define SEED
#endif
return (rand() % (end - start)) + start;
}
However, it did not work too, because, I assume, the #ifndef
only executes once at preprocessing stage.
So, after these attemps, I tried to call srand()
right at the beginning of my .h
file, but I came across with the fact that, actually you cannot call functions outside any function(main()
for example.)
In short, I am stuck right now, any help will be appreciated.