srand(NULL)

This is a discussion on srand(NULL) within the C++ Programming forums, part of the General Programming Boards category; Im just learning about random numbers, but my program generates the same numbers each time i run it. I read ...

  1. #1
    Let's do some coding! Welshy's Avatar
    Join Date
    Mar 2005
    Location
    Staffordshire University, UK
    Posts
    168

    srand(NULL)

    Im just learning about random numbers, but my program generates the same numbers each time i run it. I read i need to use this function, but im not sure how, could someone give me an example syntax in which it's used? Thanks

  2. #2
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903

    #include<cstdlib> #include<ctime>

    Code:
    srand((unsigned)time(NULL));
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    srand() seeds the random number generator. The number you pass to it decides which sequence of numbers you'll get (send the same number twice and you'll get the same sequence again). Most people get this number from time(NULL) which will return the nr of seconds since 00:00 hours, Jan 1, 1970 UTC (will practically guarantee a new number every time).

    so, once when the program starts:
    Code:
    srand(time(NULL));
    and then to get a random number:
    Code:
    int n = rand();
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Let's do some coding! Welshy's Avatar
    Join Date
    Mar 2005
    Location
    Staffordshire University, UK
    Posts
    168
    Thanks guys, i love this forum, lol

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21