Thread: random numbers

  1. #1
    vcrbstf
    Guest

    Question random numbers

    I have a random number function and when i call it in another function two different times how come it is always the same number.
    The rand function looks like this
    Code:
     
    int getRand(int i)
    {
       srand(time(NULL));
       return (rand()%i)+1;
    }
    If i call it twice for example
    Code:
    num1 = getRand(9);
    num2 = getRand(9);
    It always prints different values when the program runs but it prints the same value each time for both numbers. How come?

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    You should call srand() only once in your program.

    Some reading for you
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    8

    Heraclitus

    The reason for the numbers being the same, if I am not mistaken, is due to the fact that srand(time(NULL)) will set the random seed using the system time (in seconds). As you are calling it twice in quick succession, these two function calls will almost certainly use the same seed to produce a psuedo-random number (The "psuedo" part is why your numbers are always the same). If you pause the program for more than a second between each call, the numbers will be different... Or at least, a 1 - (1/i * 1/i) chance of being different.

    But anyway, you just need to use srand(time(NULL)) once to set a decent seed.

  4. #4
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    srand() should be used only once in your program, delele him from the function, and add him at the top of main(), this is just a suggestion.

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    No No No.... you're all wrong. The answer is you only need to call srand() once in your program.

    Now, please, lets not repeat the same answer any more
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. questions....so many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 08:47 AM
  2. Doubts regarding random numbers generation
    By girish1026 in forum C Programming
    Replies: 9
    Last Post: 12-31-2008, 10:47 PM
  3. random numbers limit
    By HAssan in forum C Programming
    Replies: 9
    Last Post: 12-06-2005, 07:51 PM
  4. Generate random numbers in Lucky7 project using C#
    By Grayson_Peddie in forum C# Programming
    Replies: 1
    Last Post: 04-11-2003, 11:03 PM
  5. random numbers
    By lil_plukyduck in forum C++ Programming
    Replies: 5
    Last Post: 01-14-2003, 10:14 PM