This is the mail archive of the cygwin@cygwin.com mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Random Number Generator


A number of problems here...

   The reason only zeroes are being output is due to everything being 
interpreted as an integer and truncating to 0 when it is less than 1.  The 
best bet make the 10 that you multiply 10.0 or else cast it as float or 
double.If you desire integer results, you can then cast input1 as int when you 
need it as such.

   Another potential problem is (RAND_MAX +1).  This overflows (gcc gives a 
warning on compile), essentially giving you (RAND_MAX * -1) on any system 
where RAND_MAX is equal to MAX_INT, which as far as I know is most systems. 
If this is deliberate, for clearer coding, it would be better to write it as 
the latter, in addition to the fact, that if the code is ever compiled on a 
system where RAND_MAX is different than MAX_INT, it will not wrap, or else it 
may wrap differently.

In short, the following line:

    input1 = rand() * 10 / (RAND_MAX + 1);

should become:

    input1 = rand() * (float)10 / (RAND_MAX);

or:

    input1 = rand() * (float)10 / (RAND_MAX * -1);

if the negation of RAND_MAX was deliberate.


Hope this helps.

Jon

> Hi!, I'm writing a program using the random number genrator rand() defined in <stdlib.h>.  I've written the following program to test it: 
> 
> 
> void main()
> {
>   int input1, i;

> 
>   srand(time(NULL));
>   
>   for (i=0; i<20 ; i++)
>     {
>       input1 = rand() * 10 / (RAND_MAX + 1);
>       printf("random numbers %i\n",input1);
> 
>     }
> } 
> 
> 
> BUT, the results I get are all zeros.  Is there something wrong with the gcc compiler provided by cygwin, because I've tested this program at university, and it outputs random numbers correctly.




-- 


-------------------------------------
  If you had a million Shakespeares,
  could they write like a monkey?


--
Want to unsubscribe from this list?
Check out: http://cygwin.com/ml/#unsubscribe-simple


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]