Thread: random numbers

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    random numbers

    How can I generate random numbers on interval [0-N]?
    I used Turbo C before and used random() function, but here I can use rand() and in that case numbers are integeres but don't konw what is upper limit
    Thanks

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    With risk of spoiling Hammer's attempt to make you read the FAQ, you should use the modulus operator %. It returns the remainder of an integer division.
    Code:
    int GetRandomNumberFromZeroToN(int N)
    {
      return rand() % (N + 1);
    }
    Doing modulus with N gives a number between 0 and N-1, so you want to do modulus with N + 1 to get a number between 0 and N.
    MagosX.com

    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. 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. Doubts regarding random numbers generation
    By girish1026 in forum C Programming
    Replies: 9
    Last Post: 12-31-2008, 10:47 PM
  3. random numbers limit
    By HAssan in forum C Programming
    Replies: 9
    Last Post: 12-06-2005, 07:51 PM
  4. Generate random numbers in Lucky7 project using C#
    By Grayson_Peddie in forum C# Programming
    Replies: 1
    Last Post: 04-11-2003, 11:03 PM
  5. random numbers
    By lil_plukyduck in forum C++ Programming
    Replies: 5
    Last Post: 01-14-2003, 10:14 PM