Could someone show me some good ways to seed the random number generator in both C and C++?

Printable View

- 09-05-2002zdudeSeeding Random Number Generator
Could someone show me some good ways to seed the random number generator in both C and C++?

- 09-05-2002zdude
I wanted to know how to do it in C++ too, randomize does not work in C++. (For me at least)

- 09-05-2002DISGUISED
Did you read the whole thing?

Quote:

*Straight from the FAQ*

That said: There is more than one way to initialize the random seed (other than randomize). Randomize will not work under all compilers. And since the seed must be initialized (or the numbers will not be random) here is the other way:

#include <stdlib.h> //for rand

#include <stdio.h> //for printf

#include <time.h> //for time

int main(void)

{

srand(time(NULL));

printf("A random number from 0 to 99: %d", rand() % 100);

return 0;

}

srand initilizes the seed based on the number inputed. Normally time() is used so that the number is different each time the program is run. If you use srand(x); (where x is equal to any constant number) you will recieve random numbers but they will be the same on each execution.

Q: But, how do i get a number between x and y? Like a die or something?

A: Use a function like this one...

int rand_mid(int low, int high)

{

return low+rand()%(high-low+1);

}