Thread: Random # everytime (my code)

  1. #1
    Registered User Paz_Rax's Avatar
    Join Date
    Jan 2004

    Question Random # everytime (my code)

    I thought of a new and easy(i think) way to come up with random numbers everytime you call a function. This seems just to easy I was wondering if anyone could find a flaw of some sort with the code:

         int Random(int min, int max){
            int *number = new int( (rand() % max) + min);
            int final = *number;
            delete number;
            return final;
    I'm sorry if this has been posted I made a quick search and found nothing.
    "Life, it's all in how you script it."

  2. #2
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Phildelphia, PA
    Your function does nothing special. There's no reason to use dynamic memory allocation there. Just seed the random number generator using the time once at the beginning of the program and call rand() as many times as you need.

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    It should be rand() % (max - min + 1), otherwise you (might) break the upper limit. And as pointed out your dynamic allocation is not neccessary. This one is also more bulletproof in case someone enters a max that is less than min.
    int Random(int Min, int Max)
      return (Max >= Min) ? ((rand() % (Max - Min + 1)) + Min) : 0;

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  2. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 04:17 PM
  3. << !! Posting Code? Read this First !! >>
    By biosx in forum C++ Programming
    Replies: 1
    Last Post: 03-20-2002, 12:51 PM
  4. Replies: 25
    Last Post: 10-28-2001, 01:08 PM