The following code outputs a random number each second:
int main ()
{
srand(time(NULL)); // Seeds number generator with execution time.
while (true)
See man 3 rand
-- you need to scale by dividing by RAND_MAX
to obtain the range [0, 1] after which you can multiply by 100 for your target range.
int rawRand = rand() % 101;
See (for more details):
rand - C++ Reference
Others have also pointed out that this is not going to give you the best distribution of random numbers possible. If that kind of thing is important in your code, you would have to do:
int rawRand = (rand() * 1.0 / RAND_MAX) * 100;
EDIT
Three years on, I'm making an edit. As others mentioned, rand()
has a great deal of issues. Obviously, I can't recommend its use when there are better alternatives going forward. You can read all about the details and recommendations here:
rand() Considered Harmful | GoingNative 2013
rawRand % 101 would give [0-100], inclusive.