Originally posted by mrukok
but im easily confused!
Code:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i;
srand(time(NULL));
i = rand();
cout << "Your random number is << i << endl;
cout<< "This compiler can generate random numbers from 0 to " << RAND_MAX;
return(0);
}
Code:
#include <iostream.h>
#include <stdlib.h>
int GetRand(int min, int max);
int main(void)
{
int i, r;
for (i = 0; i < 20; i++)
{
r = GetRand(10, 12);
cout << "Your number is " << r << ' ';
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
/*
* As Init is static, it will remember it's value between
* function calls. We only want srand() run once, so this
* is a simple way to ensure that happens.
*/
srand(time(NULL));
Init = 1;
}
/*
* Formula:
* rand() % N <- To get a number between 0 - N-1
* Then add the result to min, giving you
* a random number between min - max.
*/
rc = (rand() % (max - min + 1) + min);
return (rc);
}
Or similar