Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random Numbers?

Status
Not open for further replies.

NipsMG

Programmer
Dec 27, 2000
215
US
I'm sorry, I know this is a REALLY elementary post, but I've only recently (as in the past few days), started learning C++. (I've been a Basic/VB programmer my whole life).

I got a book on C++ and have been learning, as well as following OpenGL tutorials.. The syntax is the only major issue, however I'm not having too much of a problem following it..

What' I'm looking for is a Random Number function, that can give me a float value between 0 and 1. The only random function shown in the book I have, rand(), seems only to give integers and does not allow for the specification of a range.

I appreciate your help in advance.

Thanks!
--NipsMG
 
I have one way,but I am sure this is not a good way;
u can redefine RAND_MAX,then after u got the randrom number,
divided the Rand_Max,It works.u can write a function to do this;
 
First you got to seed the random number generator with a different seed to have different start numbers generated each time you will start the rand function

this is one method(&quot;#include <time.h>&quot;):
srand( (unsigned)time( NULL ) );

the RAND_MAX is the maximum value that can be generated. (0x7fff)

So you should be doing this to obtain numbers within 0 and 1:
float i=(float)rand()/RAND_MAX;

Hope this helps, s-)

Blessed is he who in the name of justice and good will, shepards the week through the valley of darknees...
 
To expand on BurtanI's post.... to get a number in a range (say 0-51) you would use rand()%52, for a range of 10 - 20 you would use rand()%11+10.

Matt
 
Thanks for your posts..

Zyrenthian, That's actually exactly what I figured out.

I was looking to get a float between 0 and 1, so I just used (rand() % 11 ) * 0.1f and it seemed to work fine. :)

Thanks again!

--NipsMG X-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top