srand(static_cast<unsigned int>(clock( ))); seems not random enough
Dear c/g++ programmer (on ubuntu linux 11.04):
I copied and test a simple random number generate program
-----------------
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <cstdlib>
using namespace std;
struct RndIntGen
{
RndIntGen(int l, int h)
: low(l), high(h)
{ }
int operator( )( ) const {
return low + (rand( ) % ((high - low) + 1));
}
private:
int low;
int high;
};
int main( ) {
srand(static_cast<unsigned int>(clock( )));
vector<int> v(5);
generate(v.begin( ), v.end( ), RndIntGen(1, 6));
copy(v.begin( ), v.end( ), ostream_iterator<int>(cout, "\n"));
}
--------------------------------------------------------------------
it can compile and run, and for most of people will think it run well, but for me
why it always produce same result, if it is really random and based on clock?
eric@eric-Inspiron-8600:~/cppcookbook/download$ ./a.out
2
5
4
2
6
----------------------------------------------------------
this is from Example 11-13 of book(C++ cookbook), you always can download from
http://examples.oreilly.com/9780596007614/
to test by yourself
Highly appreciate your explanation and thanks a lot in advance, Eric
|