You are here:



can you please help me with this algorithm?
"Generate random numbers between 0 and 1"
I think I have to use the RAND function but how? Please write me the codes.
Thanks a lot

Hi, Michael.

You are correct that you need to use the rand function.  The basics of rand are pretty simple: just call rand() and it'll give you a random integer between 0 and the define RAND_MAX.  The actual value of RAND_MAX varies based on implementation, but you don't really have to worry about that -- just know that RAND_MAX is guaranteed to exist as a define and you can use it regardless of its value.

What you need is a random floating point between 0 and 1, meaning you need to translate 0 -> RAND_MAX into a 0.0 -> 1.0 range.  This is a very simple process.  All you need to do is treat the result as a floating point number and divide it by RAND_MAX.  This means that a random result of 0 yields 0 (0 / anything = 0) and a random result of RAND_MAX yields 1 (anything / itself = 1).  Anything in between will be a fractional value somewhere between those numbers.  The code would look something like:

   float randFloat = float(rand()) / RAND_MAX;

To make things proper, you ought to seed the random number generator, too, so that it doesn't just yield the same results every time you execute the program.  This is done by calling the srand function (srand being shorthand for "seed random").  Usually the time is used as a seed value so that you can guarantee it to change on each execution of the program.  This line of code looks something like:


That line of code should be called once early in your program and never called again.  To have access to the time function, you will need to include the header <time.h>.

Give that a shot and if you run into problems, please do not hesitate to ask a followup.  I'm here to help. :)


All Answers

Answers by Expert:

Ask Experts


Joseph Moore


I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.


I've been writing C++ code for 12 years, both on my own in my spare time and professionally.


Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2017 All rights reserved.