Is there a diffrence between the GetTickCount() and rand() functions ? I read they both are Psuedorandom number generators , I would like to know if there is any diffrence between those two functions , I used rand() once and the output was the same each time the program run , would that change if i use GetTickCount instead ? thankyou very much :)

Recommended Answers

All 5 Replies

The reason rand() generated the same numbers each time is that you have to seed the random number generator

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
   
   int i;
   //seeds the number generator with time
   srand((unsigned int)time(NULL));//you only need to call this once in your program
   for(i = 0; i < 10; i++);
   {
      cout<<rand()<<endl;
   }

   return 0;
}

Adding on, GetTickCount() is also a way to seed the random number generator

srand( GetTickCount() );

thanx for the reply guys , i really appreciate it :)

And GetTickCount() should be something like (depending on the system) the number of 'ticks' since the machine booted. On Windows it it milliseconds since boot, and wraps around every month or two (assuming Windows can stay up that long!).

So it is 'random' in the sense that it will be different, but it is a number starting at 1 and growing every millisecond. And if you sample it twice quickly it will be the exact same value.

rand is defined as always returning the same sequence given the same seed so that you can test out your program. That is, every time your program runs it will get the same set of 'random' values so you can fix bugs and the like. Then you add srand() to give it a different seed (with time() or ticks or sampling the time deltas between keystrokes or whatever).

thanx chainsaw

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.