Thread: Resetting random numbers on the same variable...

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Seven years? civix's Avatar
    Join Date
    Jul 2002
    Posts
    605

    Resetting random numbers on the same variable...

    Alright, so im storing a random number to a variable using the GetRand function from the tutorial. What im wanting to do is get a different random number assigned to that variable..

    Code:
    #include <cstdio>
    #include <cstdlib>
    #include <iostream>
    #include <ctime>
    
    int GetRand(int min, int max)
    {
      static int Init = 0;
      int rc;
      
      if (Init == 0)
      {
        /*
         *  As Init is static, it will remember it's value between
         *  function calls.  We only want srand() run once, so this
         *  is a simple way to ensure that happens.
         */
        srand(time(NULL));
        Init = 1;
      }
    
      /*
       * Formula:  
       *    rand() &#37; N   <- To get a number between 0 - N-1
       *    Then add the result to min, giving you 
       *    a random number between min - max.
       */  
      rc = (rand() % (max - min + 1) + min);
      
      return (rc);
    }
    
    int newnumber;
    int number = getrand(1,12345);
    
    int main()
    {
      cout<<"Your current random number is: "<<number<<endl;
      cout<<"Enter '1' for a new number: ";
      cin>>newnumber;
      if(newnumber==1)
      { 
         cout<<"Your new random number is: "<<number<<endl;
      }
      system("PAUSE");
      return 0;
    }
    Please forgive the crude example program, im sure im missing a header or something. Id really appreciate any help that you all are willing to offer.
    Last edited by civix; 04-02-2008 at 07:38 PM.
    .

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. random numbers
    By mesmer in forum C Programming
    Replies: 4
    Last Post: 10-24-2008, 01:22 PM
  3. Generating a sequence of numbers in a random order
    By mirbogat in forum C Programming
    Replies: 15
    Last Post: 08-12-2008, 02:01 PM
  4. Question about random numbers
    By Kempelen in forum C Programming
    Replies: 2
    Last Post: 07-02-2008, 06:28 AM
  5. Generating 100k to 1 million unique random numbers
    By Ariod in forum C Programming
    Replies: 4
    Last Post: 08-26-2005, 12:59 PM