Thread: rand() & float

  1. #1
    Registered User
    Join Date
    Apr 2006
    Location
    Larnaca in Cyprus
    Posts
    32

    rand() & float

    I want to get random float numbers from 0 to 2 (included). How do I do this?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You could try reading the FAQ. Or maybe type that in the search box and read one of the countless posts on the topic.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Location
    Larnaca in Cyprus
    Posts
    32

    One answer by me, but I don't know if it is the best.

    num=(rand()%3) == 2 ? 2.0 : (rand()%2) + (float)(rand()%1000000)/1000000;

  4. #4
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Did you read the FAQ, How can I generate floating-point random numbers? (Like Quzah suggested)? You could also read this article on rand, which is a more general treatment of the function, as opposed to using it with floating point numbers.
    Last edited by kermit; 05-15-2010 at 07:11 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Matrix operations using objects
    By circuitbreaker in forum C++ Programming
    Replies: 7
    Last Post: 05-04-2010, 08:53 AM
  2. Replies: 2
    Last Post: 05-13-2009, 03:25 PM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM