Advertisement

How To Get a Random # between 0 and 1

Started by January 14, 2000 08:09 PM
5 comments, last by C++ Freak 24 years, 11 months ago
How do you get a random number between 0 and 1? Visit members.xoom.com/ivanickgames Edited by - C++ Freak on 1/14/00 8:12:09 PM
Visit http://members.xoom.com/ivanickgames
Here''s a nice random number generator: http://www.flipcode.com/documents/random.txt
Advertisement
Have you tried the rand() function in Visual C++?
_________________ Best regards, Sherman Chin Director Sherman3D (Malaysia) Sdn Bhd www.Sherman3D.com www.AlphaKimori.com
The functions you are looking for mainly would be rand() I believe.
rand() % 2 yields the result 1 and 0, and it requires the inclusion of .
However, to generate random numbers, you have to first provide the random number generator with a seed. Normally time(null) (the current time since a certain timeframe i can''t remember) is used as the seed, and requires the file time.h.
To set a seed, the following function, srand( time(null) ) is used.
Hope that helps
using rand() on its own generates the same random number every time the code is executed... to make sure the random number is different every time the code is exectued use something like this

#include stdlib.h
#include time.h

int num;
srand((unsigned)time(NULL));
num = rand()%2;

hope it helps. later.


Edited by - Chris F on 1/15/00 12:12:26 PM

Edited by - Chris F on 1/15/00 12:13:14 PM
"I have realised that maths can explain everything. How it can is unimportant, I want to know why." -Me
Thanks a lot guys. My code works now. I was just generating the same number every time, but now it works like a charm.
Please visit my site.

Visit members.xoom.com/ivanickgames

Edited by - C++ Freak on 1/15/00 2:14:23 PM
Visit http://members.xoom.com/ivanickgames
Advertisement
If you want floating point values between 0 and 1, then

float invRandMax = 1.0f/(float)RAND_MAX;
float randValue = ((float)rand())*invRandMax;

invRandMax only needs to be initialized once and can be used over and over when a new random value is needed. The only purpose of invRandMax is to replace divides with mults.

--Shannon Schlomer, BLAZE Technologies, Inc.
--Shannon Schlomer, BLAZE Technologies, Inc.

This topic is closed to new replies.

Advertisement