Creating random float

This is a discussion on Creating random float within the C++ Programming forums, part of the General Programming Boards category; How would I make a random number, say -2 through 2, that is a float, so it can be 2.0 ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    162

    Creating random float

    How would I make a random number, say -2 through 2, that is a float, so it can be 2.0 or -1.04783. I don't really want code, just some suggestions. Thanks a lot!

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Code is easier than writing out a longwinded explanation:
    Code:
    static double drand ( double low, double high )
    {
        return ( (double)rand() * ( high - low ) ) / (double)RAND_MAX + low;
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    162
    Hey, thanks a lot, I never knew it was so simple. This saves me a lot of thinking. :-)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help me
    By warthog89 in forum C Programming
    Replies: 11
    Last Post: 09-30-2006, 08:17 AM
  2. Replies: 6
    Last Post: 11-12-2005, 10:57 AM
  3. File input question
    By Beast() in forum C Programming
    Replies: 16
    Last Post: 07-09-2004, 03:23 PM
  4. Why does it work in Visual Studio and Not Borland
    By MonteMan in forum C++ Programming
    Replies: 14
    Last Post: 10-20-2002, 09:36 PM
  5. Need more eyes to find problem??
    By sailci in forum C++ Programming
    Replies: 2
    Last Post: 03-24-2002, 09:03 PM

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