Thread: assigning random value to a variable

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    2

    assigning random value to a variable

    I got this code from the FAQ section... I've edited the values because I only need values from 1-6.


    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    
    int GetRand(int min, int max);
    
    int main(void)
    {
      int i, r;
      
      for (i = 0; i < 1; i++)
      {
        r = GetRand(1, 6);
        printf ("Your number is &#37;d\n", r);
      }
      
      return(0);
    }
    
    int GetRand(int min, int max)
    {
      static int Init = 0;
      int rc;
      
      if (Init == 0)
      {
        srand(time(NULL));
        Init = 1;
      }
    
      rc = (rand() % (max - min + 1) + min);
      
      return (rc);
    }
    I don't understand how most of it works, especially the rand() and srand() functions, and the GetRand function. help?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  3. #3
    Registered User
    Join Date
    Jul 2007
    Posts
    2
    oooh... i get it now...! i'm just not sure if i can change the Init variable

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    Init is declared static - so it saves its value between calls.
    It is used to call srand only once per program run
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Lesson #3 - Math
    By oval in forum C# Programming
    Replies: 2
    Last Post: 04-27-2006, 08:16 AM
  3. Testing Random Number Generator
    By Roaring_Tiger in forum C Programming
    Replies: 7
    Last Post: 08-12-2005, 12:48 AM
  4. Question for Random class
    By joenching in forum C++ Programming
    Replies: 2
    Last Post: 03-20-2005, 11:22 PM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM