Thread: A Function that returns a different value each call.

  1. #1
    1479
    Join Date
    Aug 2003
    Posts
    253

    A Function that returns a different value each call.

    I am trying to get a funtion to return 5 random numbers. Here is my code:

    Code:
    #include <iostream>
    #include <ctime>      // for srand and rand()
    
    int randGenerator (  void );    // function prototype
    
    int main()
    {
    int randNum, x,y;
    
    for (x = 0; x <= 5; ++x)
    {
    randNum = randGenerator();
    std::cout <<randNum <<std::endl;
    }
    
    return 0;     // Successful termination
    }               // End main 
    
    int randGenerator( void )              // Fucntion definition
    {
    int num;
    
    srand (time(0));
    
    num = 1 + rand()  % 13;
    
    return num;
    }
    I don't understand why I keep getting the same number returned each time. I call the function 5 times and it just outputs the same number all 5 times. I tried making num a static vairable but it didn't help. I am not sure if I fully understand how function calls work. What I think is happening is the first time I call the function its sets the return value.....which is what it will be when its called again.

    How do I make it output a random number each time I call the function?
    Knowledge is power and I want it all

    -0RealityFusion0-

  2. #2
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    Code:
      srand (time(0));
    that is your problem right there, you keep seeding the randomizer with the same seed every time you call the function.

    Place that code at the top of main instead of inside of the randomizer function. You should only need to seed the randomizer once in any program (unless you need to seed it for some other reason, like encryption/decryption purposes)
    Last edited by jverkoey; 08-07-2004 at 08:46 PM.

  3. #3
    1479
    Join Date
    Aug 2003
    Posts
    253
    Ok thanks that solved my problem.
    Knowledge is power and I want it all

    -0RealityFusion0-

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. doubt in c parser coding
    By akshara.sinha in forum C Programming
    Replies: 4
    Last Post: 12-23-2007, 01:49 PM
  3. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  4. I need help with passing pointers in function calls
    By vien_mti in forum C Programming
    Replies: 3
    Last Post: 04-24-2002, 10:00 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM