Thread: still cannot generate a random number between 0 and 1

  1. #1
    Registered User
    Join Date
    May 2012
    Location
    Milwaukee
    Posts
    28

    still cannot generate a random number between 0 and 1

    It was recommended that I try this:
    Code:
    double price = 30000 *rand() % 1;
    But that keeps giving me zero every time? Am I missing something?

    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes, the recommendation is wrong. You could read Prelude's article on using rand() as a starting point.
    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
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    what does n % 1 produce?

    try a simple program that prints the results

    2 % 1
    3 % 1
    4 % 1
    5 % 1

    etc

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Are you trying to generate a random number that's EITHER 0 or 1, or are you trying to generate some sort of floating point value between 0 and 1?

    If the latter, then % and rand() are both integer-only operations and you need to find another way to do this. For example, if you wanted 2 places of precision:
    Code:
    float num = (float)((uint32_t)rand() % 100) / 100;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to generate a random number in c?
    By blogchama in forum C Programming
    Replies: 2
    Last Post: 01-20-2011, 10:39 AM
  2. Generate Random Number
    By peacealida in forum C++ Programming
    Replies: 10
    Last Post: 04-06-2008, 08:57 AM
  3. generate a random number
    By waxydock in forum C++ Programming
    Replies: 5
    Last Post: 06-05-2005, 07:43 PM
  4. Replies: 11
    Last Post: 07-16-2002, 11:39 AM
  5. Ask about generate Random number
    By ooosawaddee3 in forum C Programming
    Replies: 2
    Last Post: 07-01-2002, 04:30 AM