Understanding the algorithm of Visual C++'s rand() function

后端 未结 5 1528
渐次进展
渐次进展 2021-01-02 04:52

In C/C++, rand() and srand() are usually used by us when we want to get a random integer. But when I tried to rewrite it myself, I found it difficu

5条回答
  •  清酒与你
    2021-01-02 05:10

    Prior to calling rand, since the man page for srand indicates that "If no seed value is provided, the rand() function is automatically seeded with a value of 1", then a better approach to invoking rand is to first invoke srand which will "set its argument as the seed for a new sequence of pseudo-random integers to be returned by rand()".

    As an example, consider the following awk, nawk, gawk code which is used in a bash shell script to create a new (random) mac address - i.e. .genmacaddr referenced in code snippet:

    enter code here
    BEGIN {
         n0 = "00"
         srand()
         n1 = sprintf("%02x", int(255 * rand()))
         n2 = sprintf("%02x", int(255 * rand()))
         n3 = sprintf("%02x", int(255 * rand()))
         n4 = sprintf("%02x", int(255 * rand()))
         n5 = sprintf("%02x", int(255 * rand()))
         print n0":"n1":"n2":"n3":"n4":"n5
    }
    

    where the code snippet in the bash shell script is:

    enter code here
    ifconfig eth0 down
    newmacaddr=`nawk -f .genmacaddr -`
    ifconfig eth0 hw ether $newmacaddr
    ifconfig eth0 up
    

    If I am not mistaken, the seed value for srand is derived from the system clock.

    I hope this helps you to understand an approach to your coding solution that will work.

提交回复
热议问题