Question about rand() function

This is a discussion on Question about rand() function within the C++ Programming forums, part of the General Programming Boards category; Hi again, I read in the C++ book that rand() function returns a random number and that in order to ...

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    14

    Question about rand() function

    Hi again,

    I read in the C++ book that rand() function returns a random number and that in order to get a random number in a range that you want, the formula is:

    1-6,
    Code:
    1 + rand() % 6
    And that rand() % 6 would return 0-6, and then the +1 would make that 1-7 though?

    Also, if I run
    Code:
     rand() % 13
    it never returns 13, only 0-12, but can't you get 13 if you divide the right number as the remainder?

    Thanks again.
    Last edited by learning C++; 12-25-2003 at 01:53 PM.

  2. #2
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161

    Re: Question about rand() function

    Originally posted by learning C++
    Hi again,
    Hi

    I read in the C++ book that rand() function returns a random number and that in order to get a random number in a range that you want, the formula is:

    1-6,
    Code:
    1 + (rand() % 6) // add parens for clarity
    And that rand() % 6 would return 0-6,
    and then the +1 would make that 1-7 though?
    No, it returns 0-5, then the +1 gives 1-6

    Also, if I run
    Code:
     rand() % 13
    it never returns 13, only 0-12, but can't you get 13 if you divide the right number as the remainder?
    Don't know what you are asking here.
    The right number to get 0-13 is 14


    Thanks again.
    Welcome
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 03:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 06:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 01:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 10:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM

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