2012年1月19日 星期四

Generate random number in a loop and call srand one time when function be called

In stdlib.c, the random seed "holdrand= 1L".

If you don't change random seed,
random sequence will be same when you execute program.

To change seed can use srand().

In some situation, function will be called repeatedly.
You want to call srand() just one time, how to do??

There is a soluation.
Because the first rand() value will be 1804289383.

We can design the code:
=======================================
int GetRandomNum() {

    int tempnum = rand();
    if ( 1804289383 == tempnum ) {
        srand( time(NULL) );
    }

    for ( int i = 0 ; i < ( maxnum - minnum ) ; i++ ) {
        outValue = minnum + tempnum%( maxnum - minnum + 1 );

        if ( outValue != xx ) {
            return outValue;
        }
        tempnum = rand();
    }

}
=======================================

It will guarantee "srand()" will be executed once.
Have fun!!

沒有留言:

張貼留言