Thread: Random Integer

  1. #16
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    Code:
    srand(time(NULL));
    That's how you seed the random number generator. Because the time is somewhat random, you get a different starting-point for the random number generator every time you run your program.

    If your program has a loop, make sure you seed only once outside the loop. If the loop runs fast, it can be re-seeded with the same time, and you'll get the same "random" number more than once.

    [EDIT]
    This is from cppreference.com
    time
    Syntax:
    #include <time.h>
    time_t time( time_t *time );

    The function time() returns the current time, or -1 if there is an error. If the argument time is given, then the current time is stored in time.


    srand
    Syntax:
    #include <stdlib.h>
    void srand( unsigned seed );

    The function srand() is used to seed the random sequence generated by rand(). For any given seed, rand() will generate a specific "random" sequence over and over again.

    srand( time(NULL) );
    for( i = 0; i < 10; i++ )
    printf( "Random number #%d: %d\n", i, rand() );
    Last edited by DougDbug; 11-19-2003 at 05:01 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Access Violation
    By Graham Aker in forum C Programming
    Replies: 100
    Last Post: 01-26-2009, 08:31 PM
  2. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  3. how to generate a random integer number between 0 and 9
    By dongkhoi in forum C Programming
    Replies: 2
    Last Post: 11-07-2006, 01:49 PM
  4. Counting number from a random file
    By kamisama in forum C Programming
    Replies: 42
    Last Post: 02-22-2005, 05:16 PM
  5. random integer addition
    By strugglen in forum C++ Programming
    Replies: 2
    Last Post: 12-09-2003, 02:00 PM