Thread: how to generate random number between two numbers?

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    18

    how to generate random number between two numbers?

    How can I generate a random number between two numbers using stdlib?

    printf("%d\n", rand() % 50); generates a number between 0 and 49, but how can I generate numbers between 10 and 20 or -10 and 10 with and without decimals? Is it possible with rand() ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes, it is possible, and you basically asked this in a previous post.

    Feel free to peruse the further discussion in that post, but as I noted if you care about the quality of your PRNG, you should use a specific PRNG, not rand(). If you are satisfied with rand() despite its loose requirements, then the (rand() % (n - m + 1) + m) approach to generate a random integer in the range [m, n] is fine.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Remember that a random number between 10 and 20 is the same as a random number between 0 and 10 plus 10. i.e. Get a random number between 0 and 10 and add 10 to it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 03-12-2014, 09:47 AM
  2. the algorithm used in c++ to generate random numbers
    By karim tarbali in forum C++ Programming
    Replies: 7
    Last Post: 02-17-2012, 08:01 AM
  3. How to generate random numbers the same everytime
    By lehe in forum C++ Programming
    Replies: 11
    Last Post: 04-09-2009, 06:00 PM
  4. How to generate random numbers between 65 and 75
    By chottachatri in forum C Programming
    Replies: 19
    Last Post: 03-02-2008, 06:24 PM
  5. generate a random number
    By waxydock in forum C++ Programming
    Replies: 5
    Last Post: 06-05-2005, 07:43 PM

Tags for this Thread