assigning random value to a variable

This is a discussion on assigning random value to a variable within the C Programming forums, part of the General Programming Boards category; I got this code from the FAQ section... I've edited the values because I only need values from 1-6. Code: ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,458
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,458
    Init is declared static - so it saves its value between calls.
    It is used to call srand only once per program run
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

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, 10:22 PM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21