Thread: rand() trouble

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    10

    rand() trouble

    I'm having a bit of trouble using the random function rand(). It does kinda generate random numbers but its always the same numbers in the same order when the program starts. I read about this somewhere before but i couldnt get anything from searching the forum. The header i am using is just iostream.

    Heres where I am using the function:

    Code:
    y = (rand() % difficulty);
    I want a random number between 1 and whatever difficulty is set to (which I have been setting it to 10 when I have been using it).

    Please help!

  2. #2
    Registered User
    Join Date
    Jul 2004
    Posts
    3
    Quote Originally Posted by -Dan-
    I'm having a bit of trouble using the random function rand(). It does kinda generate random numbers but its always the same numbers in the same order when the program starts. I read about this somewhere before but i couldnt get anything from searching the forum. The header i am using is just iostream.

    Heres where I am using the function:

    Code:
    y = (rand() % difficulty);
    I want a random number between 1 and whatever difficulty is set to (which I have been setting it to 10 when I have been using it).

    Please help!
    You need to use the srand() function to seed the random number generator. The most common way to do this is:

    Code:
    srand((unsigned int)time(NULL));
    rand() is not a true random number generator, so if you don't seed it you certainly won't get a different sequence every time.

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    10
    Aaaah cheers!

Popular pages Recent additions subscribe to a feed