random numbers

This is a discussion on random numbers within the C++ Programming forums, part of the General Programming Boards category; How can I generate random numbers on interval [0-N]? I used Turbo C before and used random() function, but here ...

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

    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, 09:47 PM
  3. random numbers limit
    By HAssan in forum C Programming
    Replies: 9
    Last Post: 12-06-2005, 06: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, 09:14 PM

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