i figure out that srand() and rand() are not quite good in creating a random number.

for:

while(true){
   int x = 0;
   srand((unsigned)x);
   int r = random();

   cout<<r<<endl;
}

It gives back the same number.

Am I doing something wrong?
If not, is there anywhere that we can create our own function that call for a random number within a range, say 0 - 28?:-/

Recommended Answers

All 2 Replies

move srand() above outside that loop. It should be executed only once during the lifetime of the program. And the parameter should be time(0) so that it is different every time you run the program. Like this: srand( time(0) ); . Some compilers might want you to typecase 0 to unsigned int or size_t.

>>r = random();
Wrong. should be r = rand();

To get random values in some range, use the modulus operator as a means to limit the final value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.