Thread: Problem with function that generates random numbers

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    132

    Problem with function that generates random numbers

    Hello, everyone! I'm having a problem with the following program: I try to call the same function that generates random integers and sends it back to main() (I'm doing that because I wanna apply it to a bigger situation), but the random integers obtained are always the same, why is it happening? Thanks in advance!

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    #include <math.h>
    
    /* Function prototype: */
    int generate(void);
    
    int main(void)
    {
        printf("%d\n\n", generate());
        printf("%d\n\n", generate());
        printf("%d\n\n", generate());
    
        return 0;
    }
    
    
    
    int generate(void)
    {
        int x;
    
        srand(time(NULL));
    
        x = - 100 + rand() % 201;
    
        return x;
    }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Put srand(time(NULL)) at the beginning of main.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    132
    Thank you, it worked. Why is this necessary?

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    The random number generator used by rand() isn't really random. It's some complicated calculations that produce a sequence of pseudo-random numbers. It needs a "seed" or starting point for this calculation. That seed is by default always the same number, so you will always get the same sequence. This can actually be advantageous for testing purposes, but is otherwise bad. time(NULL) returns the current system time as an integral value. srand(time(NULL)) changes the seed to be the current system time, so every time you run it, you get a different starting point for the pseudo-random number sequence that rand() produces. Note that time() is only accurate to the second, so if you manage to run your program twice in the same second, you could get the same sequence.

  5. #5
    Registered User
    Join Date
    Oct 2010
    Posts
    132
    Thank you, anduril462.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-13-2011, 09:10 PM
  2. A C program that generates random sentences
    By ecrazed in forum C Programming
    Replies: 3
    Last Post: 07-27-2011, 10:49 PM
  3. Random Number Generator Always Generates 0 First
    By LyTning94 in forum C++ Programming
    Replies: 3
    Last Post: 06-21-2011, 03:08 PM
  4. problem with random numbers
    By xxwerdxx in forum C Programming
    Replies: 2
    Last Post: 11-24-2005, 08:56 AM
  5. Replies: 2
    Last Post: 12-25-2003, 01:31 AM