Random Numbers in c++:: update:: solved

Gooberlx2

Lifer
May 4, 2001
15,381
6
91
Hi,
I need to generate a random number between 0 and 1 using c++.

i figured it would simply be rand()%1 (seeded with the system clock ) from the stdlib.h, but that always gives me back 0.

Does rand() give back a double? ('cause I know RAND_MAX is huge).

All I need is any decimal between 0 and 1.

Any help is appreciated.

Thx
 

Gooberlx2

Lifer
May 4, 2001
15,381
6
91
I figured it out. apparently I didn't know that RAND_MAX was an int, so when I tried:

srand( time(NULL) );
float j = rand() / RAND_MAX;
cout << j << endl;

it wouldn't work. I had to CAST it. (damnd such an easy solution)

srand( time(NULL) );
float j = (float)rand() / (float)RAND_MAX;
cout << j << endl;

Yay! :)
 

PowerMacG5

Diamond Member
Apr 14, 2002
7,701
0
0
another way to do real Random Numbers is to download randgen.h and randgen.cpp (just type it in on google). The way it works is (make sure you add randgen.cpp as a node to your executable):

#include <iostream.h>
#include "randgen.h"

int main()
{
double x = 0;
RandGen r;
x = r.RandReal(0, 1);
cout << x << endl;
return 0;
}

This will give you a random real number between 0 and 1.