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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random float generation 1

Status
Not open for further replies.

qkslvrwolf

Programmer
Jul 9, 2002
28
US
Hi, I'm trying to generate some random floats, preferablly with a fairly involved post decimal presence, if you take my meaning. Currently, I've tried this...#include <stdlib.h>
#include <time.h>


int main()
{
float check;
int i;
srand((unsigned )time( NULL ));

for (i = 0; i < 20; i++)
{
check = rand()/rand();
printf(&quot;%f\n&quot;, check);
}
}

But this produces mainly produces 1's and 0's, with a few other basically integer values thrown in. The way I understood this process, this should be creating a psuedorandom number from 0 to 32 thousand something, but then I should be getting some decent floats, not all integers, shouldn't i?

 
rand() returns an int so you need to cast them in order to get the float. Try:

check = (float) rand() / (float) rand();

-Skatanic
 
Yes, but shouldn't the division take care of that? I mean, shouldn't I be able to reutnr things like 16855/155683 = some long float string? Those are both integers...
 
Let me explain with this example:

float some_float;
int some_int1, some_int2;
some_float = some_int1 / some_int2;

First, the compiler has to compute the division. Since they are both integers it does this by integer division. Then the compiler notices it needs to cast that quotient to a float. But since only integer division was done, the cast will not bring in the decimal part of the remainder. It just adds in the .0 . However, if they are casted to float BEFORE the division, the compiler does floating point division, which is what you want.

Hope this clears it up...
-Skatanic
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top