Thread: Nick help

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    Exclamation moving

    Do not call srand() more than once in one program, there is no point, especially in a fast loop where time() will be the same everytime (the measure is in seconds).

    I notice that the way my RNG works, having that srand() inside the for loop causes it to output the same number repeatedly. Moving it to where it should be:

    Code:
            srand(time(NULL));
        
        for (i = 1; ; ++i){
            random = rand() % 10;
    Made a drastic difference.

    This illustrates why you should not seed more than once. Every srand() call resets the generator, so if you call it like this:
    Code:
    	for (i=0;i<10;i++) {
    		srand(22222);
    		printf("%d\n", rand());
    	}
    You will get the exact same number 10 times. Now remember that time() will be the same for an entire second in your code.
    Last edited by MK27; 04-20-2010 at 10:17 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with my function (Heh)
    By phatsam in forum C Programming
    Replies: 9
    Last Post: 03-23-2006, 01:26 PM
  2. the new nick
    By NickESP in forum Windows Programming
    Replies: 1
    Last Post: 03-14-2003, 02:26 AM
  3. Differences in Debug and Release builds in MSVC
    By TravisS in forum C Programming
    Replies: 5
    Last Post: 06-19-2002, 10:40 PM
  4. try your heads on this
    By jasrajva in forum A Brief History of Cprogramming.com
    Replies: 70
    Last Post: 11-08-2001, 11:31 PM