C version:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
srand(time(NULL));
int i;
for(i = 0; i < 10; i++)
printf("Random number #%d: %d\n", i, rand());
C++ version:
#include <cstdlib>
#include <iostream>
#include <ctime>
std::srand(std::time(0));
for(int i = 0; i < 10; i++)
std::cout << "Random number #" << i << ": " << std::rand() << std::endl;
The function srand() is used to seed the random sequence generated by rand(). For any given seed, rand() will generate a specific "random" sequence over and over again.
In addition to Takeshi's helpful post (neither of your samples will compile, Takeshi :?), allow me to add this:
#include <stdlib.h> // if using C++, #include <cstdlib>; may not be necessary in C
#include <time.h> // if using C++, #include <ctime>
// Seed the RNG
srand(time(0));
int RandomIntInRange(int low, int high)
{
return (int)(rand() / (RAND_MAX / (double)(high - low))) + low;
}
There's probably an unnecessary cast in there, but don't disparage my parentheses -- I use them to indicate my thought processes when I come back to the code a few years down the road.
My apologies; your original C++ sample does indeed compile under MinGW32/GCC (assuming one adds a wrapping main function).
BTW, I'm very surprised that this compiles fine with no warnings under MinGW32/G++ (compiled with -Wall -W -pedantic):
#include <iostream>
int main()
{
srand(time(0));
for(int i = 0; i < 10; i++)
printf("Random number #%d: %d\n", i, rand());
}
stdlib++'s <iostream> is doing nasty things here. :shock:
Notice how srand(), rand(), and printf(), works without having to include <cstdlib>.
And <iostream> internally must be including <stdlib.h> instead of <cstdlib>, because notice how putting std:: qualifier is not requiered.
Also notice how including <ctime> was not requiered, neither qualifying time() with std::.
stdlib++'s <iostream> is doing nasty things here. :shock:
Actually, C++ headers are allowed to include as many or as few other C++ headers as they like, so it's perfectly acceptable for it to do that. This is the reason why using namespace std; is dangerous (since you have no idea which headers are being brought into scope) and why you are supposed to include the headers declaring anything you use, since you can't even ( technically ) rely on <iostream> including <istream> and <ostream>.
As for the original point of this thread:
#include <ctime>
#include <cstdlib>
void randomize() { std::srand( std::time(0) ); }
int random(int upper) { return std::rand()%(upper+1); }
( if you're using C, s/std:://g and s/<c(.+?)>/<$1.h>/g )
Note, however, that the % method of getting random numbers is actually a fairly bad pseudo-random with most crts.
The better way:
double random() { std::rand()/(RAND_MAX+1.); }
then n*random() will give you a decently pseudo-random number in [0,n)
If you want really good (pseudo-)random numbers, then use http://www.boost.org/libs/random